The Wayback Machine - https://web.archive.org/web/20240703214229/https://www.geeksforgeeks.org/fermat-method-of-primality-test/
Open In App

Fermat Method of Primality Test

Last Updated : 01 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a number n, check if it is prime or not. We have introduced and discussed the School method for primality testing in Set 1.
Introduction to Primality Test and School Method
In this post, Fermat’s method is discussed. This method is a probabilistic method and is based on 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 the given number is composite (or non-prime), then it may return true or false, but the probability of producing incorrect results 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].

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

C++




// C++ program to find the smallest twin in given range
#include <bits/stdc++.h>
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.


Python3




# Python3 program to find the smallest
# twin in given range
import random
 
# Iterative Function to calculate
# (a^n)%p in O(logy)
def power(a, n, p):
     
    # Initialize result
    res = 1
     
    # Update 'a' if 'a' >= p
    a = a % p 
     
    while n > 0:
         
        # If n is odd, multiply
        # 'a' with result
        if n % 2:
            res = (res * a) % p
            n = n - 1
        else:
            a = (a ** 2) % p
             
            # n must be even now
            n = n // 2
             
    return res % p
     
# 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
def isPrime(n, k):
     
    # Corner cases
    if n == 1 or n == 4:
        return False
    elif n == 2 or n == 3:
        return True
     
    # Try k times
    else:
        for i in range(k):
             
            # Pick a random number
            # in [2..n-2]     
            # Above corner cases make
            # sure that n > 4
            a = random.randint(2, n - 2)
             
            # Fermat's little theorem
            if power(a, n - 1, n) != 1:
                return False
                 
    return True
             
# Driver code
k = 3
if isPrime(11, k):
  print("true")
else:
  print("false")
   
if isPrime(15, k):
  print("true")
else:
  print("false")
 
# This code is contributed by Aanchal Tiwari


C#




// C# program to find the
// smallest twin in given range
using System;
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 bool 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
            Random rand = new Random();
            int a = 2 + (int)(rand.Next() % (n - 4));
          
            // Fermat's little theorem
            if (power(a, n - 1, n) != 1)
                return false;
          
            k--;
        }
      
        return true;
    }
     
  static void Main() {
        int k = 3;
        if(isPrime(11, k))
            Console.WriteLine(" true");
        else
            Console.WriteLine(" false");
        if(isPrime(15, k))
            Console.WriteLine(" true");
        else
            Console.WriteLine(" false");
  }
}
 
// This code is contributed by divyesh072019


PHP




<?php
// PHP program to find the
// smallest twin in given range
 
// Iterative Function to calculate
// (a^n)%p in O(logy)
function power($a, $n, $p)
{
     
    // Initialize result
    $res = 1;
     
    // Update 'a' if 'a' >= 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.
?>


Javascript




<script>
 
// Javascript program to find the
// smallest twin in given range
 
     
/* Iterative Function to calculate
// (a^n)%p in O(logy) */
function power( a, n, p)
{
    // Initialize result
    let 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.
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
    let a = Math.floor(Math.random()* (n-1 - 2) + 2);
     
    // Fermat's little theorem
    if (power(a, n - 1, n) != 1)
        return false;
     
    k--;
    }
     
    return true;
}
 
 
// Driver Code
 
let k = 3;
if(isPrime(11, k))
    document.write(" true" + "</br>");
else
    document.write(" false"+ "</br>");
if(isPrime(15, k))
    document.write(" true"+ "</br>");
else
    document.write(" false"+ "</br>");
 
</script>


Output: 

true
false

Time complexity: O(k Log n). Note that the power function takes O(Log n) time. 

Auxiliary Space: O(min(log a, log b))
Note that the above method may fail even if we increase the number of iterations (higher k). There exist some composite numbers with the property that for every a < n and gcd(a, n) = 1 we have 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 the key generation phase of the RSA public key cryptographic algorithm.

We will soon be discussing more methods for Primality Testing.

References: 
https://en.wikipedia.org/wiki/Fermat_primality_test 
https://en.wikipedia.org/wiki/Prime_number 
http://www.cse.iitk.ac.in/users/manindra/presentations/FLTBasedTests.pdf 
https://en.wikipedia.org/wiki/Primality_test

 



Previous Article
Next Article

Similar Reads

Introduction to Primality Test and School Method
Given a positive integer, check if the number is prime or not. A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself. Examples of the first few prime numbers are {2, 3, 5, ...}Examples : Input: n = 11Output: true Input: n = 15Output: false Input: n = 1Output: false Recommended PracticePrime NumberTry It! S
11 min read
Solovay-Strassen method of Primality Test
We have already been introduced to primality testing in the previous articles in this series. Introduction to Primality Test and School MethodFermat Method of Primality TestPrimality Test | Set 3 (Miller–Rabin) The Solovay–Strassen primality test is a probabilistic test to determine if a number is composite or probably prime. Before diving into the
15+ min read
Lucas Primality Test
A number p greater than one is prime if and only if the only divisors of p are 1 and p. First few prime numbers are 2, 3, 5, 7, 11, 13, ...The Lucas test is a primality test for a natural number n, it can test primality of any kind of number.It follows from Fermat’s Little Theorem: If p is prime and a is an integer, then a^p is congruent to a (mod
12 min read
AKS Primality Test
There are several primality test available to check whether the number is prime or not like Fermat's Theorem, Miller-Rabin Primality test and alot more. But problem with all of them is that they all are probabilistic in nature. So, here comes one another method i.e AKS primality test (Agrawal–Kayal–Saxena primality test) and it is deterministically
11 min read
Primality Test using Lucas-Lehmer Series
In this article, we will discuss the Lucas-Lehmer series which is used to check the primality of prime numbers of the form 2p - 1 where p is an integer. First, let's see what is Lucas-Lehmer series. The Lucas-Lehmer series can be expressed as : [Tex]\[s_i = \left \{ \begin{tabular}{c} 4 \hspace{1.4cm} when i = 0; \\ s_{i-1}^2 - 2 \hspace{.5cm} othe
11 min read
Vantieghems Theorem for Primality Test
Vantieghems Theorem is a necessary and sufficient condition for a number to be prime. It states that for a natural number n to be prime, the product of [Tex]2^i - 1 [/Tex]where [Tex]0 &lt; i &lt; n [/Tex], is congruent to [Tex]n~(mod~(2^n - 1)) [/Tex]. In other words, a number n is prime if and only if.[Tex]{\displaystyle \prod _{1\leq i\leq n-1}\l
4 min read
Primality test for the sum of digits at odd places of a number
Given an integer 'n', the task is to check whether the sum of digits at the odd positions (from right to left) is prime or not. If it is prime then, print "YES" or "NO" otherwise.Examples: Input: n = 123 Output: NO As, 1 + 3 = 4 is not prime.Input: n = 42 Output: YES Since, 2 is a prime. Approach: First, find the sum of the digits which are at odd
7 min read
Primality Test | Set 3 (Miller–Rabin)
Given a number n, check if it is prime or not. We have introduced and discussed School and Fermat methods for primality testing.Primality Test | Set 1 (Introduction and School Method) Primality Test | Set 2 (Fermat Method)In this post, the Miller-Rabin method is discussed. This method is a probabilistic method ( like Fermat), but it is generally pr
15+ min read
Fermat's Factorization Method
Fermat's Factorization method is based on the representation of an odd integer as the difference of two squares. For an integer n, we want a and b such as: n = a2 - b2 = (a+b)(a-b) where (a+b) and (a-b) arethe factors of the number nExample: Input: n = 6557Output: [79,83]Explanation: For the above value, the first try for a is ceil value of square
6 min read
Fermat's little theorem
Fermat's little theorem states that if p is a prime number, then for any integer a, the number a p - a is an integer multiple of p. Here p is a prime number ap ≡ a (mod p). Special Case: If a is not divisible by p, Fermat's little theorem is equivalent to the statement that a p-1-1 is an integer multiple of p. ap-1 ≡ 1 (mod p) OR ap-1 % p = 1 Here
8 min read
three90RightbarBannerImg