The Primality test
is an algorithm for determining whether a given positive integer is a prime number or not.There are many methods to check whether a number is prime or not, like, the School Method, Trial Division Method, Fermat Primality test, and Miller-Rabin Primality test.
Scope of the Article
- In this article we will discuss different
primality tests
in data structures. - All the
primality tests
are explained using steps and pseudocode in this article. - The complexity analysis of each method will also be discussed in this article.
- The programs are implemented in C++, Java, and Python in this article.
Takeaways
Algorithm for determining whether a given positive integer is a prime number or not :
- School method
- Trial Division Method
- Fermat Primality Test
- Miller-Rabin Primality Test
What is Primality Test?
The Primality test
is an algorithm for determining whether a given positive integer is a prime number or not.

The primality of a number can also be checked by determining whether it is a composite number or not, because if the number is not a composite number
nor 1
, then it must be a prime number.
Example
Source Code – C++17
// Determining whether a number is a prime or not
# include<iostream>
using namespace std;
// Function for Primality test
bool isPrime(int n){
// Corner Case
if (n<=1)
return false;
// Checking from 2 to n-1
for (int i=2; i<n; i++)
if (n % i == 0)
return false;
return true;
}
// Driver code
int main(){
int x = 3;
isPrime(x) ? cout<<x<<" is a prime number.\n": cout<<x<<" is not a prime number.\n";
int y = 12;
isPrime(y) ? cout<<y<<" is a prime number.\n": cout<<y<<" is not a prime number.\n";
}
Source Code – Java (1.8)
// Determining whether a number is a prime or not
class PrimeCheck{
// Function for Primality test
static boolean isPrime(int n){
// Corner Case
if (n<=1)
return false;
// Checking from 2 to n-1
for (int i=2; i<n; i++)
if (n % i == 0)
return false;
return true;
}
// Driver code
public static void main(String args[]){
int x = 3;
System.out.println(isPrime(x) ? (x + " is a prime number."): (x + " is not a prime number."));
int y = 12;
System.out.println(isPrime(y) ? (y + " is a prime number."): (y + " is not a prime number."));
}
}
Source Code – Python 3
# Determining whether a number is a prime or not
# Function for Primality test
def isPrime(n):
# Corner case
if n <= 1:
return False
# Checking from 2 to n-1
for i in range(2, n):
if n % i == 0:
return False
return True
# Driver code
x = 3
print(x, "is a prime number.") if isPrime(x) else print(x, "is not a prime number.")
y = 12
print(y, "is a prime number.") if isPrime(y) else print(y, "is not a prime number.")
The output is the same for all of the implementations as they peform the same thing, the only difference being the programming language.
Output
3 is a prime number.
12 is not a prime number.
In the above examples, we are checking whether the given number is a prime number or not, to do so, we are iterating from
School method
The school method
is a simple solution that comes first to everyone’s mind for primality check as it is the simplest of all.
In the School Method
algorithm, we iterate through all the numbers from

Complexity Analysis
Time Complexity:
The time complexity
of the School Method primality check is
Space Complexity:
The space complexity
here is constant.
The algorithm in the example above is School Method only.
Optimized School Method
In the School Method
, we can do some optimizations like:
- Instead of checking till
, we will check till because a factor of larger than must be a multiple of a number smaller than that has been already checked and should not be checked again. - We will first check the divisibility of
by and , then check its divisibility by numbers of the form and starting at . We do so because any integer greater than can be expressed in the form of , , , , , and (for ), but integers of the form , , , and will be divisible by or .
Let’s have a look at its implementation in the section below.
Implementation of the Optimized School Method
Source Code – C++17
// Determining whether a number is a prime or not
# include<iostream>
# include<math.h>
using namespace std;
// Function for Primality test
bool isPrime(int n){
// Corner Cases
if (n<=3)
return n>1;
else if (n%2==0 || n%3==0)
return false;
// Checking through numbers of the form 6k-1 and 6k+1 (k>0)
for (int i=5; i<sqrt(n); i+=6)
if ((n % i == 0) || (n%(i+2)==0))
return false;
return true;
}
// Driver code
int main(){
int x = 3;
isPrime(x) ? cout<<x<<" is a prime number.\n": cout<<x<<" is not a prime number.\n";
int y = 12;
isPrime(y) ? cout<<y<<" is a prime number.\n": cout<<y<<" is not a prime number.\n";
}
Source Code – Java (1.8)
// Determining whether a number is a prime or not
import java.lang.Math;
class PrimeCheck{
// Function for Primality test
static boolean isPrime(int n){
// Corner Cases
if (n<=3)
return n>1;
else if (n%2==0 || n%3==0)
return false;
// Checking through numbers of the form 6k-1 and 6k+1 (k>0)
for (int i=5; i<Math.sqrt(n); i+=6)
if ((n % i == 0) || (n % (i+2) == 0))
return false;
return true;
}
// Driver code
public static void main(String args[]){
int x = 3;
System.out.println(isPrime(x) ? (x + " is a prime number."): (x + " is not a prime number."));
int y = 12;
System.out.println(isPrime(y) ? (y + " is a prime number."): (y + " is not a prime number."));
}
}
Source Code – Python 3
# Determining whether a number is a prime or not
import math
# Function for Primality test
def isPrime(n):
# Corner cases
if n <= 3:
return n>1
elif n % 2 == 0 or n % 3 == 0:
return False
# Checking through numbers of the form 6k-1 and 6k+1 (k>0)
for i in range(5, int(math.sqrt(n)), 6):
if n % i == 0 or n % (i + 2) == 0:
return False
return True
# Driver code
x = 3
print(x, "is a prime number.") if isPrime(x) else print(x, "is not a prime number.")
y = 12
print(y, "is a prime number.") if isPrime(y) else print(y, "is not a prime number.")
The output is the same for all of the implementations as they peform the same thing, the only difference being the programming language.
Output
3 is a prime number.
12 is not a prime number.
In the above examples, we are checking whether the given number is a prime number or not, to do so, we are first checking its divisibility by
Complexity Analysis
Time complexity:
The asymptotic time complexity
of the Optimized School Method primality check is
Space Complexity:
The space complexity
here is constant.
Trial Division Method
The Trial Division Method
is a primality check algorithm in which we accept some integer 2
to

Complexity Analysis
Time complexity:
The time complexity
of The Trial Division primality check is
Space Complexity:
The space complexity
here is constant.
Fermat Primality Test
The Fermat Primality
test is a probabilistic method to determine whether the given integer is a probable prime number or not.
It is based on Fermat's Little Theorem
that states if
If we want to test
Algorithm Steps
- Repeat the following
times (higher value of indicates higher probability of correct results):- Handle corner cases for
( is the number to be tested). - Pick a random number
in the range . - If
, then return .
- Handle corner cases for
- Return
, is probably a prime number.
Example
Let us assume, we have to check whether
For
Now there can be two cases,
but,
This proves that
Complexity Analysis
Time Complexity
:
Here,
Space Complexity
:
There is no need for extra space, so the space complexity is constant.
The Fermat’s little theorem is used for one more Primality test, called the Miller-Rabin Primality Test.
Miller-Rabin Primality Test
The Miller-Rabin Primality Test
is also a probabilistic method to determine whether the given integer is a prime number or not, similar to the Fermat Primality Test. It is also based on the Fermat’s Little Theorem (discussed in the above section).
This test was discovered by Gary Lee Miller in 1976
, later modified by Michael Oser Rabin in 1980
.
The result of this test will be whether the given number is a composite number or a probable prime number. The probable prime numbers in the Miller-Rabin Primality Test
are called strong probable numbers, as they have a higher chance of being a prime number than in the Fermat's Primality Test
.
A number
Algorithm Steps
- Handle base cases for
. - if
is even, return . - Find an odd number
. - Loop the following
times:- Check if
, if yes, return .
- Check if
- Return
.
- Pick a random number
in the range . - Compute
. - Return
if . - Loop the following till
. .- Return
if . - Return
if .
Implementation of the Miller-Rabin Primality Test
Source Code – C++17
// Determining whether a number is a prime or not
# include<iostream>
# include<math.h>
using namespace std;
// Function for modular exponentiation. It returns (x^y) % p
int pow(int x, unsigned int y, int p){
int res = 1;
// Update x if it is more than or equal to p
x = x % p;
while (y > 0)
{
// If y is odd, multiply x with result
if (y & 1)
res = (res*x) % p;
y = y>>1; // y = y/2
x = (x*x) % p;
}
return res;
}
// This function is called for all k trials.
bool millerRabinTest(int d, int n){
// Pick a random number in [2,n-2]
// n > 4, because of the corner cases
int a = 2 + rand() % (n - 4);
// Computing a^d % n
int x = pow(a, d, n);
if (x == 1 || x == n-1)
return true;
// Keep squaring x till:
// (i) (x^2) % n is not 1
// (ii) (x^2) % n is not n-1
while (d != n-1){
x = (x * x) % n;
d *= 2;
if (x == 1) return false;
if (x == n-1) return true;
}
// Return composite
return false;
}
// Function for Primality test
bool isPrime(int n, int k){
// Corner Cases
if (n<=3)
return n>1;
else if (n==4)
return false;
// Finding r such that n = 2^d * r + 1, (r > 0)
int d = n - 1;
while (d % 2 == 0)
d /= 2;
// Iterating k times
for (int i = 0; i < k; i++)
if (!millerRabinTest(d, n))
return false;
return true;
}
// Driver code
int main(){
int k = 10;
int x = 3;
isPrime(x, k) ? cout<<x<<" is probably a prime number.\n": cout<<x<<" is a composite number.\n";
int y = 12;
isPrime(y, k) ? cout<<y<<" is probably a prime number.\n": cout<<y<<" is a composite number.\n";
int z = 541;
isPrime(z, k) ? cout<<z<<" is probably a prime number.\n": cout<<z<<" is a composite number.\n";
}
Source Code – Java (1.8)
// Determining whether a number is a prime or not
import java.math.*;
class PrimeCheck{
// Function for modular exponentiation. It returns (x^y) % p
static int power(int x, int y, int p) {
int res = 1;
// Update x if it is more than or equal to p
x = x % p;
while (y > 0) {
// If y is odd, multiply x with result
if ((y & 1) == 1)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
// This function is called for all k trials.
static boolean millerRabinTest(int d, int n) {
// Pick a random number in [2,n-2]
// n > 4, because of the corner cases
int a = 2 + (int)(Math.random() % (n - 4));
// Computing a^d % n
int x = power(a, d, n);
if (x == 1 || x == n - 1)
return true;
// Keep squaring x till:
// (i) (x^2) % n is not 1
// (ii) (x^2) % n is not n-1
while (d != n - 1) {
x = (x * x) % n;
d *= 2;
if (x == 1)
return false;
if (x == n - 1)
return true;
}
// Return composite
return false;
}
// Function for Primality test (returns True if the given number is probably prime and False if it is a composite.)
static boolean isPrime(int n, int k){
// Corner Cases
if (n<=3)
return n>1;
else if (n==4)
return false;
// Finding r such that n = 2^d * r + 1, (r > 0)
int d = n - 1;
while (d % 2 == 0)
d /= 2;
// Iterating k times
for (int i = 0; i < k; i++)
if (!millerRabinTest(d, n))
return false;
return true;
}
// Driver code
public static void main(String args[]){
int k = 10;
int x = 3;
System.out.println(isPrime(x, k) ? (x + " is probably a prime number."): (x + " is a composite number."));
int y = 12;
System.out.println(isPrime(y, k) ? (y + " is probably a prime number."): (y + " is a composite number."));
int z = 541;
System.out.println(isPrime(z, k) ? (z + " is probably a prime number."): (z + " is a composite number."));
}
}
Source Code – Python 3
# Determining whether a number is a prime or not
import random
# This function is called for all k trials.
def millerRabinTest(d, n):
# Pick a random number in [2,n-2]
# n > 4, because of the corner cases
a = 2 + random.randint(1, n - 4);
# Compute a^d % n
x = a**d%n
if (x == 1 or x == n - 1):
return True;
# Keep squaring x till:
# (i) (x^2) % n is not 1
# (ii) (x^2) % n is not n-1
while (d != n - 1):
x = (x * x) % n;
d *= 2;
if (x == 1):
return False;
if (x == n - 1):
return True;
# Return composite
return False;
# Function for Primality test (returns True if the given number is probably prime and False if it is a composite.)
def isPrime(n, k):
# Corner cases
if n <= 3:
return n>1
elif n==4:
return False
# Finding r such that n = 2^d * r + 1, (r > 0)
d = n - 1;
while d % 2 == 0:
d //= 2;
# Iterating k times
for i in range(k):
if (millerRabinTest(d, n) == False):
return False;
return True;
# Driver code
k = 10
x = 3
print(x, "is probably a prime number.") if isPrime(x, k) else print(x, "is a composite number.")
y = 12
print(y, "is probably a prime number.") if isPrime(y, k) else print(y, "is a composite number.")
z = 541
print(z, "is probably a prime number.") if isPrime(z, k) else print(z, "is a composite number.")
The output is the same for all of the implementations as they peform the same thing, the only difference being the programming language.
Output
3 is probably a prime number.
12 is a composite number.
541 is probably a prime number.
In the above examples, we are checking whether the given number is a probable prime number or a composite number, to do so, we are using the Miller-Rabin Primality Test. If the function returns
The Miller-Rabin Test, being an extension of the Fermat’s Primality Test, is more accurate than Fermat’s Primality Test, thus, it is preferred over that.
Complexity Analysis
Time Complexity:
The time complexity
of the Miller-Rabin Primality Test is
Space Complexity:
There is no need for extra space, so the space complexity is constant.
Conclusion
Primality tests
are used to determine whether a given number is a prime or not.- The School method is a naive algorithm of
time complexity. - The Optimized School method and the Trial Division algorithm have a time complexity of
. - The
Fermat's Primality test
and Miller-Rabin Primality test return whether a number is composite or a probable prime, and are based on Fermat’s Little Theorem. - The time complexity of the
Fermat's Primality Theorem
is . - The time complexity of the
Miller-Rabin Primality Test
is .