Given a number n, check if it is prime or not. We have introduced and discussed School method for primality testing in Set 1.
In this post, Fermat’s method is discussed. This method is a probabilistic method and is based on below Fermat’s Little Theorem.
Fermat's Little Theorem: If n is a prime number, then for every a, 1 <= a < n, an-1 ≡ 1 (mod n) OR an-1 % n = 1 Example: Since 5 is prime, 24 ≡ 1 (mod 5) [or 24%5 = 1], 34 ≡ 1 (mod 5) and 44 ≡ 1 (mod 5) Since 7 is prime, 26 ≡ 1 (mod 7), 36 ≡ 1 (mod 7), 46 ≡ 1 (mod 7) 56 ≡ 1 (mod 7) and 66 ≡ 1 (mod 7) Refer this for different proofs.
If a given number is prime, then this method always returns true. If given number is composite (or non-prime), then it may return true or false, but the probability of producing incorrect result for composite is low and can be reduced by doing more iterations.
Below is algorithm:
// Higher value of k indicates probability of correct // results for composite inputs become higher. For prime // inputs, result is always correct 1) Repeat following k times: a) Pick a randomly in the range [2, n - 2] b) If an-1 ≢ 1 (mod n), then return false 2) Return true [probably prime].
Below is the implementation of above algorithm. The code uses power function from Modular Exponentiation
Time complexity of this solution is O(k Log n). Note that power function takes O(Log n) time.
Note that the above method may fail even if we increase number of iterations (higher k). There exist sum composite numbers with the property that for every a < n, an-1 ≡ 1 (mod n). Such numbers are called Carmichael numbers. Fermat’s primality test is often used if a rapid method is needed for filtering, for example in key generation phase of the RSA public key cryptographic algorithm.
We will soon be discussing more methods for Primality Testing.
This article is contributed by Ajay. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Improved By : jit_t
- Primality Test | Set 3 (Miller–Rabin)
- Primality Test | Set 1 (Introduction and School Method)
- Euler’s Totient Function
- Sieve of Eratosthenes
- Modular Exponentiation (Power in Modular Arithmetic)
- Number of Permutations such that no Three Terms forms Increasing Subsequence
- Check if the first and last digit of the smallest number forms a prime
- Print all substring of a number without any conversion
- Complement of a number with any base b
- Check if Decimal representation of an Octal number is divisible by 7