Primality Test in C++


In this problem, we are given a number N and our task is to check whether it is a prime number or not.

Primality test s the algorithm that is used to check whether the given number is prime or not.

Prime number is a number which can be divided by itself only. Example : 2, 3, 5, 7.

Let’s take an example to understand our problem,

Input: 11
Output: Yes

There are multiple methods to check for primality test of a number.

One simple method to check for primality is by checking the division of the number by all numbers less than N. If any number divides N, then it is not a prime number.

Check for all i = 2 - n-1. If n/i == 0, its not a prime number.

This method can be made more efficient by making these small changes in the algorithm.

First, we should check for values till √n instead of n. This will save a lot of loop values. √n include values of all probable factors of n.

Other change could be checking division by 2 and 3. Then checking of loop values from 5 to √n.

Program to show the implementation of this algorithm

Example

 Live Demo

#include <iostream>
using namespace std;
bool isPrimeNumber(int n){
   if (n <= 1)
      return false;
   if (n <= 3)
   return true;
   if (n % 2 == 0 || n % 3 == 0)
      return false;
   for (int i = 5; i * i <= n; i = i + 6)
   if (n % i == 0 || n % (i + 2) == 0)
   return false;
   return true;
}
int main() {
   int n = 341;
   if (isPrimeNumber(n))
      cout<<n<<" is prime Number.";
   else
      cout<<n<<" is not prime Number.";
   return 0;
}

Output

341 is not prime Number.

Other more effective method to check from the primality of a number is using Fermat’s method which is based on Fermat’s Little Theorem.

Fermat’s Little Theorem  For a prime number N, Every value of x belonging to (1, n-1). The below is true,

a n-1 ≡ 1 (mod n)
or
a n-1 % n = 1

Program to show implementation of this theorem,

Example

 Live Demo

#include <iostream>
#include <math.h>
using namespace std;
int power(int a, unsigned int n, int p) {
   int res = 1;
   a = a % p;
   while (n > 0){
      if (n & 1)
      res = (res*a) % p;
      n = n/2;
      a = (a*a) % p;
   }
   return res;
}
int gcd(int a, int b) {
   if(a < b)
      return gcd(b, a);
   else if(a%b == 0)
      return b;
   else return gcd(b, a%b);
}
bool isPrime(unsigned int n, int k) {
   if (n <= 1 || n == 4) return false;
   if (n <= 3) return true;
   while (k>0){
      int a = 2 + rand()%(n-4);
      if (gcd(n, a) != 1)
         return false;
      if (power(a, n-1, n) != 1)
         return false;
      k--;
   }
   return true;
}
int main() {
   int k = 3, n = 23;
   if(isPrime(n, k)){
      cout<<n<<" is a prime number";
   }
   else
      cout<<n<<" is not a prime number";
   return 0;
}

Output

23 is a prime number

Updated on: 03-Feb-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements