【问题标题】:Checking primality of very large numbers in Python在 Python 中检查非常大数的素数
【发布时间】:2016-04-09 20:16:06
【问题描述】:

检查给定大数是否为素数的最快方法是什么?我说的是大约 10^32 大小的数字。我已经尝试过the great answer by @MarcoBonelli 的算法,即:

from math import sqrt; from itertools import count, islice

def isPrime(n):
    return n > 1 and all(n%i for i in islice(count(2), int(sqrt(n)-1)))

但是当用于如此大的数字时,它会给出Stop argument for islice() must be None or an integer: 0 <= x <= sys.maxsize 的错误。那么有什么不同的快速方法呢?

【问题讨论】:

    标签: python primes


    【解决方案1】:

    这是我的米勒-拉宾素性检验的实现;它默认为 5 次随机试验,但您可以根据需要进行调整。 p 上的循环是小素数的快速返回。

    def isPrime(n, k=5): # miller-rabin
        from random import randint
        if n < 2: return False
        for p in [2,3,5,7,11,13,17,19,23,29]:
            if n % p == 0: return n == p
        s, d = 0, n-1
        while d % 2 == 0:
            s, d = s+1, d/2
        for i in range(k):
            x = pow(randint(2, n-1), d, n)
            if x == 1 or x == n-1: continue
            for r in range(1, s):
                x = (x * x) % n
                if x == 1: return False
                if x == n-1: break
            else: return False
        return True
    

    【讨论】:

      【解决方案2】:

      对于中等大的数字,我会使用 Miller-Rabin 的 Primality 检验。你可以在这里找到它的 Python 代码:https://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test#Python

      请注意,该算法本质上是概率性的,但多次应用它可以保证以非常高的概率正确回答。

      如果您绝对要使用基于试除法的方法,我建议您将大量小素数相乘并存储得到的合数。然后,您可以使用标准算法(例如“fraction.gcd”)获取最大公约数 (GCD)。如果答案不是 1,那么测试的数字肯定不是素数。通常你会应用上面的 Miller-Rabin 检验来确定它是否是素数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-19
        • 1970-01-01
        • 2010-11-11
        • 2020-02-23
        • 2019-05-16
        相关资源
        最近更新 更多