fermat数推素数无穷
The Fermat test is based on a result from number theory known as Fermat’s little theorem.
Fermat检验基于称为费马小定理的数论结果。
According to Fermat’s little theorem, if n is a prime number and d is any positive integer less than n, then d raised to the nth power is congruent to d modulo n.
根据费马小定理,如果n是素数,并且d是小于n的任何正整数,则d升至n的幂等于d的模n 。
If two numbers have the same remainder when divided by n then they are said to be congruent modulo n. d modulo n is simply the remainder of a number d when divided by n.
如果两个数字除以n的 余数相同,则称它们为n模 。 ð 模n是简单地将一个数d的剩余部分时除以n。
For example, 34 is congruent to 16 (modulo 3) as 34 modulo 3 = 1 and 16 modulo 3 = 1.
例如,当34模3 = 1和16模3 = 1时,34等于16(模3)。
费马检验素数 (Fermat test for primality)
For a given number n, pick a random positive number d such that d <; n.
对于给定的数字n ,选择一个随机正数d ,使d < ; 。
Calculate (d^n) modulo n.
计算(d ^ n)模n 。
d modulo n is always going to be d as we always pick d that satisfies the condition d <; n.
ð模n为总是将d作为我们总是选择d满足条件d <; 。
If the result of (d^n) modulo n is not equal to d, then d is certainly not prime.
如果(d ^ n)模n的结果不等于d ,则d当然不是素数。
If the result of (d^n) modulo n is equal to d, then the chances are good that n is prime.
如果(d ^ n)模n的结果等于d ,那么n是素数的机会就很大。
Pick another random d that satisfies the condition d < n and repeat the above steps.
选择另一个满足条件d < n的随机数d ,然后重复上述步骤。
Note: The examples in this post use Swift 4.1
注意 :本文中的示例使用Swift 4.1
We need a function to calculate the exponential of a number modulo another number.
我们需要一个函数来计算另一个模的个数的指数。
We use modular exponentiation to compute values when the exponent is greater than 1 as this lets us perform computation while only dealing with numbers less than n (modulo in the above function).
当指数大于1时,我们使用模幂运算来计算值,因为这使我们能够执行计算,而只处理小于n的数字(上述函数为模 )。
The Fermat test chooses at random a number d between 1 and n-1 (number — 1 in the above function) inclusive. The aim is to check whether the remainder modulo n of the nth power of d is equal to d.
Fermat测试随机选择一个介于1和n-1之间的数字d (在上述函数中, 数字-1 ),包括两端。 目的是检查d的n次幂的余数n是否等于d。
The Fermat test is run for the specified count. If a number fails the Fermat test, we are assured that it is not prime. If a number passes the Fermat test, it is not guaranteed to be prime. We try to reduce the probability of error in our primality test by running the test enough times.
针对指定计数运行Fermat测试。 如果某个数字未通过Fermat测试,则可以确定它不是素数。 如果数字通过了Fermat测试,则不能保证它是质数。 我们尝试通过运行足够多次来减少素数测试中的错误概率。
By trying more and more values of d (a random positive number between 1 and n-1), we can increase our confidence in the result.
通过尝试越来越多的d值(介于1和n-1之间的随机正数),我们可以提高对结果的信心。
fermat数推素数无穷