
- 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
C++ Program to Perform Fermat Primality Test
Fermat Primality test performs to check a given number is prime or not. Here is a C++ code of this algorithm.
Algorithm
Begin modulo(base, e, mod) a = 1 b = base while (e > 0) if (e mod 2 == 1) a = (a * b) % mod b = (b * b) % mod e = e / 2 return a % mod End Begin Fermat(ll m, int iterations) if (m == 1) return false done for (int i = 0; i < iterations; i++) ll x = rand() mod (m - 1) + 1 if (modulo(x, m - 1, m) != 1) return false done return true End
Example Code
#include <cstring> #include <iostream> #include <cstdlib> #define ll long long using namespace std; ll modulo(ll base, ll e, ll mod) { ll a = 1; ll b = base; while (e > 0) { if (e % 2 == 1) a = (a * b) % mod; b = (b * b) % mod; e = e / 2; } return a % mod; } bool Fermat(ll m, int iterations) { if (m == 1) { return false; } for (int i = 0; i < iterations; i++) { ll x = rand() % (m - 1) + 1; if (modulo(x, m - 1, m) != 1) { return false; } } return true; } int main() { int iteration = 70; ll num; cout<<"Enter integer to test primality: "; cin>>num; if (Fermat(num, iteration)) cout<<num<<" is prime"<<endl; else cout<<num<<" is not prime"<<endl; return 0; }
Output
Enter integer to test primality: 13 is prime
- Related Articles
- C++ Program to Perform Baillie-PSW Primality Test
- Primality Test in C++
- Primality test of numbers in JavaScript
- C++ Program to Implement the Solovay-Strassen Primality Test to Check if a Given Number is Prime
- C++ Program to Implement the Rabin-Miller Primality Test to Check if a Given Number is Prime
- How to perform fisher test in R?
- How to perform Friedman test in R?
- How to Perform Bartlettís Test in Python?
- How To Perform Dunnís Test In Python?
- Primality test for the sum of digits at odd places of a number in C++
- How to perform one sample Kolmogorov-Smirnov test in R?
- How to perform post hoc test for Kruskal-Wallis in R?
- How to perform paired t test for multiple columns in R?
- Fermat's Last Theorem in C++
- Fermat's little theorem in C++

Advertisements