Fermat theorem: For prime number p and any integer A, there is a^p≡a (mod p) (congruence). Conversely, if A^p≡a (mod p) is satisfied, p also has a large probability of being prime. A a^ (p-1) ≡1 (mod p) will be asked to go to both sides at the same time.
That is to say, suppose we want to test whether n is a prime number. We can randomly pick a number a, and then calculate a^ (n-1) mod n, if the result is not 1, we can 100% to conclude that N is not prime.
Otherwise we will randomly select a new number A to test. So repeatedly, if each result is 1, we assume that N is prime.
This test is known as the Fermat test . It is important to note that the Fermat test is not necessarily accurate, and it is possible to have a case where composite is misjudged as a prime number.
Miller and Rabin in the Fermat test, the Miller-rabin prime number test algorithm is established.
A two-time detection theorem was added compared to the Fermat test:
If P is an odd prime, the solution for x^2≡1 (mod p) is x≡1 or x≡p-1 (mod p)
If a^ (n-1) ≡1 (mod n) is established, the Miller-rabin algorithm does not immediately find another a to test, but to see if n-1 is an even number. If the n-1 is an even number, another u= (n-1)/2, and check whether the two-time detection theorem is met a^u≡1 or a^u≡n-1 (mod n).
For example on a Matrix67 blog, suppose n=341, the a=2 we chose. The first Test, 2^340 mod 341=1. Since 340 is an even number, we check the 2^170 and get 2^170 mod 341=1, which satisfies the two-time detection theorem. And since 170 is still even, we check the 2^85 mod 341=32 further. The two detection theorem is not satisfied at this time, so it is possible to determine that 341 is not prime.
Combining these two theorems is the most common miller-rabin test.
But one Mr Test still has a certain error rate. To make our results as accurate as possible, we need to perform multiple Mr Tests so that the error rate can be reduced.
Prime number Test