
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Fermat's little theorem in C++
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,
ap ≡ 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 ap ≡ 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)
=> 36 ≡ 729
=> 729 - 1 = 728
=> 728 / 7 = 104
Program to illustrate the working of theorem,
Example
#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!
- Related Articles
- C++ Program to Implement Fermat’s Little Theorem
- What is Fermat’s Little Theorem in Information Security?
- Midy’s theorem in C++
- Lagrange’s four square theorem in C++
- Bayes Theorem for Conditional Probability in C/C++
- Extended Midy's theorem in C++
- Fermat's Last Theorem in C++
- An application on Bertrandís ballot theorem in C/C++
- C++ Program to Implement Euler Theorem
- C++ Program to Implement the Vizing’s Theorem
- C++ Program for Zeckendorf's Theorem?
- Little Oh Notation (o)
- Carnots Theorem
- How do I convert between big-endian and little-endian values in C++?
- Explain Arden’s Theorem in TOC.

Advertisements