# Primality Test | Set 2 (Fermat Method)

Given a number n, check if it is prime or not. We have introduced and discussed School method for primality testing in Set 1.

Primality Test | Set 1 (Introduction and School Method)

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-1,

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 gcd(a, n) ≠ 1, then return false
c) If an-1 &nequiv; 1 (mod n), then return false
2) Return true [probably prime]. ```

## Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.

Below is the implementation of above algorithm. The code uses power function from Modular Exponentiation

## C++

 `// C++ program to find the smallest twin in given range ` `#include ` `using` `namespace` `std; ` ` `  `/* Iterative Function to calculate (a^n)%p in O(logy) */` `int` `power(``int` `a, unsigned ``int` `n, ``int` `p) ` `{ ` `    ``int` `res = 1;      ``// Initialize result ` `    ``a = a % p;  ``// Update 'a' if 'a' >= p ` ` `  `    ``while` `(n > 0) ` `    ``{ ` `        ``// If n is odd, multiply 'a' with result ` `        ``if` `(n & 1) ` `            ``res = (res*a) % p; ` ` `  `        ``// n must be even now ` `        ``n = n>>1; ``// n = n/2 ` `        ``a = (a*a) % p; ` `    ``} ` `    ``return` `res; ` `} ` ` `  `/*Recursive function to calculate gcd of 2 numbers*/` `int` `gcd(``int` `a, ``int` `b) ` `{ ` `    ``if``(a < b) ` `        ``return` `gcd(b, a); ` `    ``else` `if``(a%b == 0) ` `        ``return` `b; ` `    ``else` `return` `gcd(b, a%b);   ` `} ` ` `  `// If n is prime, then always returns true, If n is ` `// composite than returns false with high probability ` `// Higher value of k increases probability of correct ` `// result. ` `bool` `isPrime(unsigned ``int` `n, ``int` `k) ` `{ ` `   ``// Corner cases ` `   ``if` `(n <= 1 || n == 4)  ``return` `false``; ` `   ``if` `(n <= 3) ``return` `true``; ` ` `  `   ``// Try k times ` `   ``while` `(k>0) ` `   ``{ ` `       ``// Pick a random number in [2..n-2]         ` `       ``// Above corner cases make sure that n > 4 ` `       ``int` `a = 2 + ``rand``()%(n-4);   ` ` `  `       ``// Checking if a and n are co-prime ` `       ``if` `(gcd(n, a) != 1) ` `          ``return` `false``; ` `  `  `       ``// Fermat's little theorem ` `       ``if` `(power(a, n-1, n) != 1) ` `          ``return` `false``; ` ` `  `       ``k--; ` `    ``} ` ` `  `    ``return` `true``; ` `} ` ` `  `// Driver Program to test above function ` `int` `main() ` `{ ` `    ``int` `k = 3; ` `    ``isPrime(11, k)?  cout << ``" true\n"``: cout << ``" false\n"``; ` `    ``isPrime(15, k)?  cout << ``" true\n"``: cout << ``" false\n"``; ` `    ``return` `0; ` `} `

## Java

 `// Java program to find the  ` `// smallest twin in given range ` ` `  `import` `java.io.*; ` `import` `java.math.*; ` ` `  `class` `GFG { ` `     `  `    ``/* Iterative Function to calculate ` `    ``// (a^n)%p in O(logy) */` `    ``static` `int` `power(``int` `a,``int` `n, ``int` `p) ` `    ``{ ` `        ``// Initialize result ` `        ``int` `res = ``1``; ` `         `  `        ``// Update 'a' if 'a' >= p ` `        ``a = a % p;  ` `     `  `        ``while` `(n > ``0``) ` `        ``{ ` `            ``// If n is odd, multiply 'a' with result ` `            ``if` `((n & ``1``) == ``1``) ` `                ``res = (res * a) % p; ` `     `  `            ``// n must be even now ` `            ``n = n >> ``1``; ``// n = n/2 ` `            ``a = (a * a) % p; ` `        ``} ` `        ``return` `res; ` `    ``} ` `     `  `    ``// If n is prime, then always returns true,  ` `    ``// If n is composite than returns false with  ` `    ``// high probability Higher value of k increases ` `    ``//  probability of correct result. ` `    ``static` `boolean` `isPrime(``int` `n, ``int` `k) ` `    ``{ ` `    ``// Corner cases ` `    ``if` `(n <= ``1` `|| n == ``4``) ``return` `false``; ` `    ``if` `(n <= ``3``) ``return` `true``; ` `     `  `    ``// Try k times ` `    ``while` `(k > ``0``) ` `    ``{ ` `        ``// Pick a random number in [2..n-2]      ` `        ``// Above corner cases make sure that n > 4 ` `        ``int` `a = ``2` `+ (``int``)(Math.random() % (n - ``4``));  ` `     `  `        ``// Fermat's little theorem ` `        ``if` `(power(a, n - ``1``, n) != ``1``) ` `            ``return` `false``; ` `     `  `        ``k--; ` `        ``} ` `     `  `        ``return` `true``; ` `    ``} ` `     `  `    ``// Driver Program  ` `    ``public` `static` `void` `main(String args[]) ` `    ``{ ` `        ``int` `k = ``3``; ` `        ``if``(isPrime(``11``, k)) ` `            ``System.out.println(``" true"``); ` `        ``else` `            ``System.out.println(``" false"``); ` `        ``if``(isPrime(``15``, k)) ` `            ``System.out.println(``" true"``); ` `        ``else` `            ``System.out.println(``" false"``); ` `             `  `    ``} ` `} ` ` `  `// This code is contributed by Nikita Tiwari. `

## PHP

 `= p ` `    ``\$a` `= ``\$a` `% ``\$p``;  ` ` `  `    ``while` `(``\$n` `> 0) ` `    ``{ ` `         `  `        ``// If n is odd, multiply  ` `        ``// 'a' with result ` `        ``if` `(``\$n` `& 1) ` `            ``\$res` `= (``\$res` `* ``\$a``) % ``\$p``; ` ` `  `        ``// n must be even now ` `        ``\$n` `= ``\$n` `>> 1; ``// n = n/2 ` `        ``\$a` `= (``\$a` `* ``\$a``) % ``\$p``; ` `    ``} ` `    ``return` `\$res``; ` `} ` ` `  `// If n is prime, then always  ` `// returns true, If n is ` `// composite than returns  ` `// false with high probability ` `// Higher value of k increases ` `// probability of correct ` `// result. ` `function` `isPrime(``\$n``, ``\$k``) ` `{ ` `     `  `    ``// Corner cases ` `    ``if` `(``\$n` `<= 1 || ``\$n` `== 4)  ` `    ``return` `false; ` `    ``if` `(``\$n` `<= 3)  ` `    ``return` `true; ` `     `  `    ``// Try k times ` `    ``while` `(``\$k` `> 0) ` `    ``{ ` `         `  `        ``// Pick a random number  ` `        ``// in [2..n-2]  ` `        ``// Above corner cases  ` `        ``// make sure that n > 4 ` `        ``\$a` `= 2 + rand() % (``\$n` `- 4);  ` `     `  `        ``// Fermat's little theorem ` `        ``if` `(power(``\$a``, ``\$n``-1, ``\$n``) != 1) ` `            ``return` `false; ` `     `  `        ``\$k``--; ` `    ``} ` ` `  `    ``return` `true; ` `} ` ` `  `// Driver Code ` `\$k` `= 3; ` `\$res` `= isPrime(11, ``\$k``) ? ``" true\n"``: ``" false\n"``; ` `echo``(``\$res``); ` ` `  `\$res` `= isPrime(15, ``\$k``) ? ``" true\n"``: ``" false\n"``; ` `echo``(``\$res``); ` ` `  `// This code is contributed by Ajit. ` `?> `

Output:

```true
false
```

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 some composite numbers with the property that for every a < n, gcd(a, n) = 1 and 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.