# 此函数用于求解雅克比符号(利用性质求解) # n&1 与运算 可以判断n是否为偶数:如果是偶数,n&1,返回0;否则返回1,为奇数 defjacobi(n, m):# calc Jacobi(n/m) n = n%m if n == 0: return0 Jacobi2 = 1 ifnot (n&1): # 若有n为偶数, 计算Jacobi2 = Jacobi(2/m)^(s) 其中n = 2^s*t t为奇数 k = (-1)**(((m**2-1)//8)&1) whilenot (n&1): Jacobi2 *= k n >>= 1 if n == 1: return Jacobi2 return Jacobi2 * (-1)**(((m-1)//2*(n-1)//2)&1) * jacobi(m%n, n)
defSolovay_Stassen(n, t): if n == 2or n == 3: returnTrue if n % 2 == 0: returnFalse for _ inrange(t): b = random.randint(2, n-2) m = int((n-1)//2) r = pow(b, m, n) if(r != 1and r != n-1): returnFalse if r == n-1: r = -1 s = jacobi(b, n) if(r != s): returnFalse returnTrue
defmain(): n = int(input("请输入需要检测的数字:"))
t = int(input("请输入循环轮数:")) start = time.perf_counter() if Solovay_Stassen(n, t): print("%d 可能为素数" % n) else: print("%d 为合数" % n) end = time.perf_counter() print("time is :%.5f" % (end - start))
x = pow(b, int(d), n) if x == 1or x == n - 1: returnFalse for _ inrange(s - 1): x = pow(x, 2, n) if x == n - 1: returnFalse returnTrue
defmiller_rabin(n, t): if n == 2or n == 3: returnTrue if n % 2 == 0: returnFalse s = 0 d = n-1 while d % 2 == 0: s += 1 d = d // 2 for _ inrange(t): b = random.randrange(2, n-1) if is_primes(b, d, s, n): returnFalse returnTrue
defmain(): n = int(input("请输入需要检测的数字:"))
t = int(input("请输入循环轮数:")) start = time.perf_counter() if miller_rabin(n, t): print("%d 可能为素数"% n) else: print("%d 为合数"%n) end = time.perf_counter() print("time is :%.5f" % (end - start))