C++ Program to Implement Fermat’s Little Theorem

C++Server Side ProgrammingProgramming

Fermat's little theorem is one of the fundamental results of elementary number theory and is the basis for the Fermat primality test. The theorem is named after Pierre de Fermat, who stated it in 1640. The 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.


   Function power() is used to compute a raised to power b under modulo M
   function modInverse() to find modular inverse of a under modulo m :
   Let m is prime
   If a and m are relatively prime, then
      modulo inverse is a^(m - 2) mod m

Example Code

#include <iostream>
using namespace std;
int pow(int a, int b, int M) {
   int x = 1, y = a;
   while (b > 0) {
      if (b % 2 == 1) {
         x = (x * y);
         if (x > M)
            x %= M;
      y = (y * y);
      if (y > M)
         y %= M;
         b /= 2;
   return x;
int modInverse(int a, int m) {
   return pow(a, m - 2, m);
int main() {
   int a, m;
   cout<<"Enter number to find modular multiplicative inverse: ";
   cout<<"Enter Modular Value: ";
   cout<<modInverse(a, m)<<endl;


Enter number to find modular multiplicative inverse: 26
Enter Modular Value: 7
Published on 15-Mar-2019 15:54:37