【发布时间】:2020-03-16 11:07:57
【问题描述】:
我试图在 python 中执行Miller-Rabin Primality Test。我已经根据维基百科上的pseudocode 编写了如下代码:
from math import *
from numpy import *
def Miller_Rabin(n, k): #Miller-Rabin Primality Test
if n == 2 or n == 3:
return True
if n % 2 == 0:
return False
s = n - 1
d = 0
r = 0
while True:
if s % 2 == 0:
r += 1
s /= 2
else:
d = s
break
for i in range(k):
a = random.randint(2, n-1)
t = a**d
x = t % n
if x == 1 or x == n-1:
continue
for j in range(r-1):
x = x**2 % n
if x == n-1:
continue
return False
return True
但是当我运行代码并输入一个像 5336101 这样的素数时,我得到了以下错误:
File "C:\Users\kienp\Documents\Math Projects\Primality Test\primality_test.py", line 46, in Miller_Rabin
t = a**d
OverflowError: (34, 'Result too large')
所以我决定使用 Decimal 模块,修改了几行代码:
- 添加部分:
from decimal import Decimal #Adding
from decimal import Context #Adding
- 修改部分:
for i in range(k):
a = random.randint(2, n-1)
t = Decimal(Decimal(a)**Decimal(d))
x = Decimal(t) % n
然后我又遇到了一个错误:
File "C:\Users\kienp\Documents\Math Projects\Primality Test\primality_test.py", line 46, in Miller_Rabin
t = Decimal(Decimal(a)**Decimal(d))
decimal.Overflow: [<class 'decimal.Overflow'>]
我该如何解决这个问题?
【问题讨论】:
标签: python primality-test