Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Miller-Rabin测试慢Python_Python - Fatal编程技术网

Miller-Rabin测试慢Python

Miller-Rabin测试慢Python,python,Python,因此,我从中阅读了伪代码,并认为用python编写它会很酷。所以我写了这个: n = input('Enter a number to test ') n = int(n) a=int(5) d = n - 1 s = 0 while (d % 2 == 0): s = s + 1 d = int(d/2) x = a**d x = x % n if (x==1 or x==(n-1)): print("probably prime") r = int(1) while(r&l

因此,我从中阅读了伪代码,并认为用python编写它会很酷。所以我写了这个:

n = input('Enter a number to test ')
n = int(n)
a=int(5)
d = n - 1
s = 0
while (d % 2 == 0):
   s = s + 1
   d = int(d/2)
x = a**d
x = x % n
if (x==1 or x==(n-1)):
   print("probably prime")
r = int(1)
while(r<(s-1)):
   x = x**2
   x = x%n
   if (x==1):
      print ("composite")
   if (x==(n-1)):
      print ("probably prime")
print("if nothing above is printed n is composite")
n=input('输入要测试的数字')
n=int(n)
a=int(5)
d=n-1
s=0
而(d%2==0):
s=s+1
d=整数(d/2)
x=a**d
x=x%n
如果(x==1或x==(n-1)):
打印(“可能是素数”)
r=int(1)

而(r链接代码中的第二个循环最多只进行5次迭代,而您的循环类似于log(n)

编辑:
甚至更多-永远不会修改“r”变量,因此循环的退出条件永远不会满足。退出循环的唯一可能性是中断。

您还应该替换:

x = a**d
x = x % n
与:


它的模幂运算速度比简单的方法快得多,因为它在每次乘法时取模,而不是建立一个大数然后取模。

我的错误!我忘记了在循环过程中加r=r+1。我觉得很愚蠢,你为什么要写
r=int(1)
1
已经是一个int;您不需要对它调用
int
。@user2357112坏习惯:(这可能是一个注释。
x = pow(a, d, n)