Miller-Rabin素性测试(Python实现)
import random def fast_power(base, power, n): result = 1 tmp = base while power > 0: if power&1 == 1: result = (result * tmp) % n tmp = (tmp * tmp) % n power = power>>1 return result def Miller_Rabin(n, iter_num): # 2 is prime if n == 2: return True # if n is even or less than 2, then n is not a prime if n&1 == 0 or n<2: return False # n-1 = (2^s)m m,s = n - 1,0 while m&1==0: m = m>>1 s += 1 # M-R test for _ in range(iter_num): b = fast_power(random.randint(2,n-1), m, n) if b==1 or b== n-1: continue for __ in range(s-1): b = fast_power(b, 2, n) if b == n-1: break else: return False return True if __name__ == "__main__": # example print(Miller_Rabin(49139, 10)) print(Miller_Rabin(561, 10))
相关推荐
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
夜斗不是神 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16
坚持是一种品质 2020-11-16
染血白衣 2020-11-16
huavhuahua 2020-11-20
meylovezn 2020-11-20
逍遥友 2020-11-20
weiiron 2020-11-16