我正在为正在执行的某个项目实施Miller-Rabin primality checker。但是,该算法不适用于诸如101、103、107、109之类的质数...我不知道问题出在哪里。预先感谢您提供的所有帮助。
def miller_rabin_is_prime(number, k=10):
if number < 2:
return False
elif number <= 3:
return True
else:
odd_num, power_of_two, factor_out = 0, 0, number - 1
while number != (2 ** power_of_two)*odd_num + 1:
if factor_out / 2 == int(factor_out / 2):
power_of_two += 1
factor_out /= 2
else:
odd_num = (number - 1) / (2 ** power_of_two)
for _ in range(k):
random = randint(2, number - 2)
checker = (random**odd_num) % number
if (checker == 1) or (checker == number - 1):
continue
try:
for loop in range(power_of_two - 1):
checker = (checker**2) % number
if checker == number - 1:
raise TypeError
except TypeError:
continue
return False
return True
我希望101的输出为True,但实际输出为False。
答案 0 :(得分:1)
如果您替换
odd_num = (number - 1) / (2 ** power_of_two)
作者
odd_num = (number - 1) // (2 ** power_of_two)
您的代码可以正常工作-但对于较大的代码来说相当慢。要改善代码:
odd_num
和power_of_two
pow()
进行模幂运算。类似的东西:
from random import randint
def miller_rabin_is_prime(number, k=10):
if number < 2:
return False
elif number <= 3:
return True
else:
odd_num = number - 1
power_of_two = 0
while odd_num % 2 == 0:
power_of_two += 1
odd_num //= 2
for _ in range(k):
random = randint(2, number - 2)
checker = pow(random,odd_num, number)
if (checker == 1) or (checker == number - 1):
continue
try:
for loop in range(power_of_two - 1):
checker = pow(checker,2,number)
if checker == number - 1:
raise TypeError
except TypeError:
continue
return False
return True
然后,例如,miller_rabin_is_prime(1000003)
几乎会立即求值为True
,而您的原始代码(即使在/
被//
替换之后)也需要大约15秒因为是非模幂。
最后,您要对非错误条件使用错误处理(显然,checker == number - 1
时没有类型错误)。重构主循环以便不使用try--except
会更加干净。错误处理并不意味着普通的控制流程。