python实现基于米勒拉宾素性检测算法最快的超大数素性检测
0x00 米勒拉宾素性检测算法伪代码
米勒拉宾素性检测算法的伪代码:
Input #1: n > 3, an odd integer to be tested for primality;
Input #2: k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 = (2 ^ r) * d with d odd by factoring powers of 2 from n − 1
WitnessLoop: repeat k times:
pick a random integer a in the range [2, n − 2]
x ← a^d mod n
if x = 1 or x = n − 1 then
continue WitnessLoop
repeat r − 1 times:
x ← x^2 mod n
if x = 1 then
return composite
if x = n − 1 then
continue WitnessLoop
return composite
return probably prime
0x01 实现
一开始针对这个米勒拉宾素性检测算法里的幂模运算,我以为用蒙哥马利算法-快速幂模要比pow()函数更快,结果还是内置的pow()更快:
|
|
上面的伪代码中a的选取是可以优化的,可以看到下面代码有实现,原理看一下wikipedia:
|
|
0x02 测试
用这个方法检测素数,100位10进制数平均0.0003,1000位10进制数平均0.09秒,10000位10进制数平均60秒。
0x03 完整代码
|
|