Fermat's little theorem in C++

C++Server Side ProgrammingProgramming

Fermat’s little theorem −

This theorem states that for any prime number p,

Ap - p is a multiple of p.

This statement in modular arithmetic is denoted as,

a ≡ a (mod p)

If a is not divisible by p then,

ap - 1 ≡ 1 (mod p)

In this problem, we are given two numbers a and p. Our task is to verify fermat’s little theorem on these values.

We need to check if a ≡ a (mod p) or ap - 1 ≡ 1 (mod p)

Holds true for the given values of a and p.

Let’s take an example to understand the problem,

Input: a = 3, p = 7

Output: True

Explanation:

Ap-1  ≡ 1 (mod p)

=> 3≡ 729

=> 729 - 1 = 728

=> 728 / 7 = 104

Program to illustrate the working of theorem,

Example

Live Demo

#include <iostream>
#include <math.h>
using namespace std;

int fermatLittle(int a, int p) {

int powVal;
if(a % p == 0){

powVal = pow(a, p);
if((powVal - p) % p == 0){
cout<<"Fermat's little theorem holds true!";
}
else{
cout<<"Fermat's little theorem holds false!";
}
}
else {
powVal = pow(a, (p - 1));
if((powVal - 1) % p == 0 ){
cout<<"Fermat's little theorem holds true!";
}
else{
cout<<"Fermat's little theorem holds false!";
}
}

}

int main()
{
int a = 3, m = 11;
fermatLittle(a, m);
return 0;
}

Output −

Fermat's little theorem holds true!
Updated on 22-Jan-2021 13:45:58