我有Miller-Rabin的实施
def MillerRabin(n,a):
e = 0
q = n-1
while q % 2 == 0:
e += 1
q = q/2
if a**q % n == 1:
return 1
for i in range(e):
if a ** (q * 2 ** i) % n == n-1:
return 1
return 0
(n, minA, maxA) = map(int, sys.argv[1:4])
print [MillerRabin(n, a) for a in range(minA,maxA)]
有三个输入:number,min-base,max-base。数量低时功能正常。但是当数字太大时,我得到一个错误(测试用例是数字= 12530759607784496010584573923,min-base = 16,max-base = 32)
exponent must be at most 9223372036854775807
答案 0 :(得分:1)
使用内置pow
功能。它可以采用可选的mod参数
>>> help(pow)
Help on built-in function pow in module __builtin__:
pow(...)
pow(x, y[, z]) -> number
With two arguments, equivalent to x**y. With three arguments,
equivalent to (x**y) % z, but may be more efficient (e.g. for longs).
def MillerRabin(n, a):
e = 0
q = n-1
while q % 2 == 0:
e += 1
q = q // 2
if pow(a, q, n) == 1:
return 1
for i in range(e):
if pow(a , (q * 2 ** i) , n) == n - 1:
return 1
return 0