The Wayback Machine - https://web.archive.org/web/20240717024547/https://www.geeksforgeeks.org/fermats-little-theorem/
Open In App

Fermat’s little theorem

Last Updated : 21 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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 a is not divisible by p. 


Take an Example How Fermat’s little theorem works 


 Example 1:

 P = an integer Prime number   
 a = an integer which is not multiple of P  
 Let a = 2 and P = 17 
 
 According to Fermat's little theorem 
  2 17 - 1     ≡ 1 mod(17)
 we got  65536 % 17 ≡ 1   
 that mean (65536-1) is an multiple of 17 

Example 2:

Find the remainder when you divide 3^100,000 by 53.

Since, 53 is prime number we can apply fermat's little theorem here.
Therefore:     3^53-1 ≡ 1 (mod 53)
            3^52 ≡ 1   (mod 53)
Trick: Raise both sides to a larger power so that it is close to 100,000.
            100000/52 = Quotient = 1923 and remainder = 4.Multiplying both sides with 1923:            (3^52)^1923 ≡ 1^1923 (mod 53)                    3^99996 ≡ 1  (mod 53)Multiplying both sides with 3^4:                3^100,000 ≡ 3^4  (mod 53)                3^100,000 ≡ 81   (mod 53)                3^100,000 ≡ 28   (mod 53).Therefore, the remainder is 28 when you divide 3^100,000 by 53.

Use of Fermat’s little theorem

If we know m is prime, then we can also use Fermat’s little theorem to find the inverse.

        am-1 ≡ 1 (mod m) 

If we multiply both sides with a-1, we get

        a-1 ≡ a m-2 (mod m) 

Below is the Implementation of above :

C++

// C++ program to find modular inverse of a
// under modulo m using Fermat's little theorem.
// This program works only if m is prime.
#include <bits/stdc++.h>
using namespace std;
 
// To compute x raised to power y under modulo m
int power(int x, unsigned int y, unsigned int m);
 
// Function to find modular inverse of a under modulo m
// Assumption: m is prime
void modInverse(int a, int m)
{
    if (__gcd(a, m) != 1)
        cout << "Inverse doesn't exist";
 
    else {
 
        // If a and m are relatively prime, then
        // modulo inverse is a^(m-2) mode m
        cout << "Modular multiplicative inverse is "
             << power(a, m - 2, m);
    }
}
 
// To compute x^y under modulo m
int power(int x, unsigned int y, unsigned int m)
{
    if (y == 0)
        return 1;
    int p = power(x, y / 2, m) % m;
    p = (p * p) % m;
 
    return (y % 2 == 0) ? p : (x * p) % m;
}
 
// Driver Program
int main()
{
    int a = 3, m = 11;
    modInverse(a, m);
    return 0;
}

                    

Java

// Java program to find modular
// inverse of a under modulo m
// using Fermat's little theorem.
// This program works only if m is prime.
 
class GFG {
    static int __gcd(int a, int b)
    {
 
        if (b == 0) {
            return a;
        }
        else {
            return __gcd(b, a % b);
        }
    }
 
    // To compute x^y under modulo m
    static int power(int x, int y, int m)
    {
        if (y == 0)
            return 1;
        int p = power(x, y / 2, m) % m;
        p = (p * p) % m;
 
        return (y % 2 == 0) ? p : (x * p) % m;
    }
 
    // Function to find modular
    // inverse of a under modulo m
    // Assumption: m is prime
    static void modInverse(int a, int m)
    {
        if (__gcd(a, m) != 1)
            System.out.print("Inverse doesn't exist");
 
        else {
 
            // If a and m are relatively prime, then
            // modulo inverse is a^(m-2) mode m
            System.out.print(
                "Modular multiplicative inverse is "
                + power(a, m - 2, m));
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int a = 3, m = 11;
        modInverse(a, m);
    }
}
 
// This code is contributed by Anant Agarwal.

                    

Python3

# Python program to find
# modular inverse of a
# under modulo m using
# Fermat's little theorem.
# This program works
# only if m is prime.
 
 
def __gcd(a, b):
 
    if(b == 0):
        return a
    else:
        return __gcd(b, a % b)
 
# To compute x^y under modulo m
 
 
def power(x, y, m):
 
    if (y == 0):
        return 1
    p = power(x, y // 2, m) % m
    p = (p * p) % m
 
    return p if(y % 2 == 0) else (x * p) % m
 
# Function to find modular
# inverse of a under modulo m
# Assumption: m is prime
 
 
def modInverse(a, m):
 
    if (__gcd(a, m) != 1):
        print("Inverse doesn't exist")
 
    else:
 
        # If a and m are relatively prime, then
        # modulo inverse is a^(m-2) mode m
        print("Modular multiplicative inverse is ",
              power(a, m - 2, m))
 
# Driver code
 
 
a = 3
m = 11
modInverse(a, m)
 
# This code is contributed
# by Anant Agarwal.

                    

C#

// C# program to find modular
// inverse of a under modulo m
// using Fermat's little theorem.
// This program works only if m is prime.
using System;
 
class GFG {
    static int __gcd(int a, int b)
    {
 
        if (b == 0) {
            return a;
        }
        else {
            return __gcd(b, a % b);
        }
    }
 
    // To compute x^y under modulo m
    static int power(int x, int y, int m)
    {
        if (y == 0)
            return 1;
        int p = power(x, y / 2, m) % m;
        p = (p * p) % m;
 
        return (y % 2 == 0) ? p : (x * p) % m;
    }
 
    // Function to find modular
    // inverse of a under modulo m
    // Assumption: m is prime
    static void modInverse(int a, int m)
    {
        if (__gcd(a, m) != 1)
            Console.WriteLine(
                "Modular multiplicative inverse is "
                + power(a, m - 2, m));
 
        else {
 
            // If a and m are relatively prime, then
            // modulo inverse is a^(m-2) mode m
            Console.WriteLine(
                "Modular multiplicative inverse is "
                + power(a, m - 2, m));
        }
    }
 
    // Driver code
    public static void Main()
    {
        int a = 3, m = 11;
        modInverse(a, m);
    }
}
 
// This code is contributed by vt_m.

                    

PHP

<?php
// PHP program to find modular inverse of a
// under modulo m using Fermat's little theorem.
// This program works only if m is prime.
 
 
// To compute x raised to
// power y under modulo m
// Recursive function to
// return gcd of a and b
function __gcd($a, $b)
{
     
    // Everything divides 0
    if ($a == 0 || $b == 0)
    return 0;
 
    // base case
    if ($a == $b)
        return $a;
 
    // a is greater
    if ($a > $b)
        return __gcd($a-$b, $b);
    return __gcd($a, $b-$a);
}
 
// Function to find modular
// inverse of a under modulo m
// Assumption: m is prime
function modInverse($a, $m)
{
    if (__gcd($a, $m) != 1)
        echo "Inverse doesn't exist";
 
    else
    {
 
        // If a and m are relatively
        // prime, then modulo inverse
        // is a^(m-2) mode m
        echo "Modular multiplicative inverse is ",
                             power($a,$m - 2, $m);
    }
}
 
// To compute x^y under modulo m
function power($x, $y, $m)
{
    if ($y == 0)
        return 1;
    $p = power($x,$y / 2, $m) % $m;
    $p = ($p * $p) % $m;
 
    return ($y % 2 == 0) ? $p : ($x * $p) % $m;
}
 
    // Driver Code
    $a = 3; $m = 11;
    modInverse($a, $m);
     
// This code is contributed by anuj__67.
?>

                    

Javascript

<script>
 
 
// Javascript program to find modular inverse of a
// under modulo m using Fermat's little theorem.
// This program works only if m is prime.
 
function __gcd(a, b)
{
    if(b == 0)
    {
        return a;
    }
    else
    {
        return __gcd(b, a % b);
    }
}
// Function to find modular inverse of a under modulo m
// Assumption: m is prime
function modInverse(a, m)
{
    if (__gcd(a, m) != 1)
        document.write( "Inverse doesn't exist");
 
    else {
 
        // If a and m are relatively prime, then
        // modulo inverse is a^(m-2) mode m
        document.write( "Modular multiplicative inverse is "
             + power(a, m - 2, m));
    }
}
 
// To compute x^y under modulo m
function power(x, y, m)
{
    if (y == 0)
        return 1;
    var p = power(x, parseInt(y / 2), m) % m;
    p = (p * p) % m;
 
    return (y % 2 == 0) ? p : (x * p) % m;
}
 
// Driver Program
var a = 3, m = 11;
modInverse(a, m);
 
// This code is contributed by rutvik_56.
</script>

                    

Output : 
 

Modular multiplicative inverse is 4

Time Complexity: O(log m)

Auxiliary Space: O(log m) because of the internal recursion stack.

Some Article Based on Fermat’s little theorem 
 



Previous Article
Next Article

Similar Reads

Compute nCr%p using Fermat Little Theorem
Given three numbers n, r and p, compute the value of nCr mod p. Here p is a prime number greater than n. Here nCr is Binomial Coefficient.Example: Input: n = 10, r = 2, p = 13 Output: 6 Explanation: 10C2 is 45 and 45 % 13 is 6. Input: n = 6, r = 2, p = 13 Output: 2Recommended PracticenCrTry It! We have discussed the following methods in previous po
15+ min read
Analysis of algorithms | little o and little omega notations
The main idea of asymptotic analysis is to have a measure of the efficiency of algorithms that don’t depend on machine-specific constants, mainly because this analysis doesn’t require algorithms to be implemented and time taken by programs to be compared. We have already discussed Three main asymptotic notations. The following 2 more asymptotic not
4 min read
Fermat's Last Theorem
According to Fermat's Last Theorem, no three positive integers a, b, c satisfy the equation, [Tex]a^n + b^n = c^n [/Tex]for any integer value of n greater than 2. For n = 1 and n = 2, the equation have infinitely many solutions. Some solutions for n = 1 are, 2 + 3 = 5 7 + 13 = 20 5 + 6 = 11 10 + 9 = 19 Some solutions for n = 2 are, [Tex]5^2 + 12^2
5 min read
What is Endianness? Big-Endian & Little-Endian
Computers operate using binary code, a language made up of 0s and 1s. This binary code forms the foundation of all computer operations, enabling everything from rendering videos to processing complex algorithms. A single bit is a 0 or a 1, and eight bits make up a byte. While some data, such as certain English characters, can be represented by a si
5 min read
Cook–Levin theorem or Cook's theorem
In computational complexity theory, the Cook–Levin theorem, also known as Cook's theorem, states that the Boolean satisfiability problem is NP-complete. That is, it is in NP, and any problem in NP can be reduced in polynomial time by a deterministic Turing machine to the Boolean satisfiability problem. Stephen Arthur Cook and L.A. Levin in 1973 ind
4 min read
Compute nCr % p | Set 4 (Chinese Remainder theorem with Lucas Theorem)
Given three numbers n, r and p, the task is to compute the value of nCr % p. Note: p is a square-free number and the largest prime factor of p â‰Ī 50. Examples: Input: n = 10, r = 2, p = 13Output: 6Explanation: 10C2 is 45 and 45 % 13= 6 Input: n = 6, r = 2, p = 13Output: 2 Approach: We have already discussed several other approaches of this problem.
10 min read
Check if a number is Fermat Pseudoprime
Given a number N and a base number A. The task is to check whether the number is a Fermat Pseudoprime to the base. The number N is called as Fermat Pseudoprime to the base A, if 1. A &gt; 1 2. N is a composite number 3. N divides AN-1 - 1. Examples: Input : N = 645, a = 2 Output :1 645 = 3*5*43, Hence it is a composite number Also 645 divides 2^(64
7 min read
Program to find first N Fermat Numbers
Fermat numbers are non-negative odd numbers which is valid for all values of k&gt;=0. Only the first seven terms of the sequence are known till date. First, five terms of the series are prime but rest of them are not. The kth term of Fermat number is represented as The sequence: 3, 5, 17, 257, 65537, 4294967297, 18446744073709551617 For a given N,
6 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 Method of Primality Test
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 MethodIn 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, t
10 min read
three90RightbarBannerImg