【问题标题】:Fermat primality test too slow - issues with big integers费马素性检验太慢 - 大整数的问题
【发布时间】:2021-02-18 04:00:11
【问题描述】:

这是我的费马素性检验代码:

def fermat(n):
    counter = 0
    prime = False
    if n >= 40:
        upper_bound = 40
    else:
        upper_bound = n - 1

    for a in range(2, upper_bound + 1):
        print(a)
        if pow_mod(a, n - 1, n) == 1:
            counter += 1

    if counter == n - 2 and upper_bound == n - 1 or counter == 39 and upper_bound == 40:
        prime = True

    return prime

pow_mod 函数通过重复乘法计算 a^b mod n,每次应用 mod n,如下所示:

def pow_mod(a, b, n):
        result = 1
        for i in range(b):
            result = result * a % n
        return result

它适用于相对较小的素数。但是,如果我运行它以获取较大的质数,例如 67280421310721,它不会在所需的时间内产生结果。是因为人数多吗?我该如何解决这个问题?

【问题讨论】:

    标签: python math primes


    【解决方案1】:

    这是因为您的pow_mod 非常慢。使用 fast algorithm 或只使用 Python 的内置 pow 函数。

    顺便说一句,如果我正确理解了您相当复杂的代码,那么您只是在检查 所有 测试是否成功。哪个写的更清楚:

    def fermat(n):
        upper_bound = 40 if n >= 40 else n - 1
        return all(pow(a, n - 1, n) == 1
                   for a in range(2, upper_bound + 1))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-03
      • 1970-01-01
      • 1970-01-01
      • 2020-09-25
      • 2011-04-30
      • 1970-01-01
      • 2013-10-16
      • 1970-01-01
      相关资源
      最近更新 更多