如果你看过 Algorithms by S. Dasgupta, C. H. Papadimitriou, and U. V. Vazirani,里面素性检验的部分有关于检测大质数的方式
第一次看到简直毁我三观,概率检测?
Testing k = 100 values of a makes the probability of failure at most 2^−100, which is miniscule: far less, for instance, than the probability that a random cosmic ray will sabotage the computer during the computation!
用 Python 实现的话,大致是这样的:
def primality(n):
"""give a positive integer n, testing primality.
With the power of Fermat's little theorem, we can use a probabilistic tests
that it makes the probability of failure at most 2^(-100).
"""
if n <= 102:
for a in xrange(2, n):
if pow(a, n - 1, n) != 1:
return False
return True
else:
for i in xrange(100):
a = random.randint(2, n - 1)
if pow(a, n - 1, n) != 1:
return False
return True