The Wayback Machine - https://web.archive.org/web/20250203113827/https://www.geeksforgeeks.org/check-for-prime-number/
Open In App

Check for Prime Number

Last Updated : 27 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

You are given a number n. Check whether it is a Prime number or not.

Input: n = 10
Output: false
Explanation: 10 is divisible by 2 and 5

Input: n = 11
Output: true
Explanation: 11 is divisible by 1 and 11 only

Input: n = 1
Output: false
Explanation: 1 is neither composite nor prime

Input: n = 0
Output: false
Explanation: 0 is neither composite nor prime

Different Methods to Check for Prime Number

To check if a number is prime, we can use the key property of prime numbers that is, a prime number has exactly two factors, 1 and itself. If a number has more than two factors, it is not considered prime.

[Naive Approach] Basic Trial Division Method - O(n) Time and O(1) Space

The simplest method to check if a number n is prime by checking every number from 2 to n-1.

  • If n is less than 2, return false (0 and 1 are not prime).
  • If the number n is divisible by any of these, it's not prime.
  • If no divisors are found, return true.
C++
#include <iostream>
using namespace std;

bool isPrime(int n) {
    if (n <= 1)
        return false;

    // Check divisibility from 2 to n-1
    for (int i = 2; i < n; i++)
        if (n % i == 0)
            return false;

    return true;
}

int main() {
    int n = 11;
  	if(isPrime) cout << "true";
  	else cout<<"false";
    return 0;
}
C
#include <stdio.h>
#include <stdbool.h>

bool isPrime(int n) {
    if (n <= 1)
        return false;

    // Check divisibility from 2 to n-1
    for (int i = 2; i < n; i++)
        if (n % i == 0)
            return false;

    return true;
}

int main() {
    int n = 11;
    if( isPrime(n)) printf("%s","true");
  	else printf("%s","false");
    return 0;
}
Java
 class GfG {

    static boolean isPrime(int n) {
        if (n <= 1)
            return false;

        // Check divisibility from 2 to n-1
        for (int i = 2; i < n; i++)
            if (n % i == 0)
                return false;

        return true;
   }

    public static void main(String[] args) {
        int n = 11;
      	if(isPrime(n)){
        	System.out.println("true");
        }else{
          System.out.println("false");
    	}
	}
}
Python
def isPrime(n):
    if n <= 1:
        return False

    # Check divisibility from 2 to n-1
    for i in range(2, n):
        if n % i == 0:
            return False

    return True

if __name__ == "__main__":
  n = 11
  if(isPrime(n)): 
    print("true")
  else:
    print("false")
C#
using System;

class GfG {
    static bool IsPrime(int n) {
        if (n <= 1)
            return false;

        // Check divisibility from 2 to n-1
        for (int i = 2; i < n; i++)
            if (n % i == 0)
                return false;

        return true;
    }

    static void Main(string[] args) {
        int n = 11;
      	if(IsPrime(n))
           Console.WriteLine("true");
      	else
          Console.WriteLine("false");
    }
}
JavaScript
function isPrime(n) {
    if (n <= 1)
        return false;

    // Check divisibility from 2 to n-1
    for (let i = 2; i < n; i++)
        if (n % i === 0)
            return false;

    return true;
}

// Driver Code
let n = 11;
if(isPrime(n))
	console.log("true");
else
	console.log("false");

Output
true

Time Complexity: O(n)
Auxiliary Space: O(1)

[Efficient Approach - 1] Trial Division Method - O(√n) time and O(1) space

There is an observation that if we take any number n and find its divisors then divisors would appear in pairs. For example, if 4 is a divisor of 28, then 28/4=7 is also a divisor. So we have the pair (4,7).

This means that for any divisor d of n, there is a corresponding divisor n/d. If d is less than or equal to the √n, then n/d will be greater than or equal to the √n. Therefore, we only need to check for divisors up to the √n. If n has a divisor larger than its square root, the paired divisor must be smaller than the square root, which we would have already checked.

For example, if n = 36, its square root is 6. The divisors are 1,2,3,4,6,9,12,18,36. We only need to check 1,2,3,4,6 because any larger divisor will have a smaller paired divisor that we've already checked.

C++14
#include <iostream>
#include <cmath>
using namespace std;

// Function to check whether a number is prime or not
bool isPrime(int n) {

    // Numbers less than or equal to 1 are not prime
    if (n <= 1)
        return false;

    // Check divisibility from 2 to the square root of n
    for (int i = 2; i <= sqrt(n); i++)
        if (n % i == 0)  
            return false;

    // If no divisors were found, n is prime
    return true;
}

int main() {
    int n = 11;  
  	if(isPrime) cout << "true";
  	else cout<<"false";
    return 0;
}
C
#include <stdio.h>
#include <stdbool.h>
#include <math.h>

bool isPrime(int n) {
    // Numbers less than or equal to 1 are not prime
    if (n <= 1)
        return false;

    // Check divisibility from 2 to the square root of n
    for (int i = 2; i <= sqrt(n); i++)
        if (n % i == 0)  
            return false;

    // If no divisors were found, n is prime
    return true;
}

int main() {
    int n = 11; 
    if( isPrime(n)) printf("%s","true");
  	else printf("%s","false");
    return 0;
}
Java
class GfG {
    static boolean isPrime(int n) {

        // Numbers less than or equal to 1 are not prime
        if (n <= 1)
            return false;

        // Check divisibility from 2 to the square root of n
        for (int i = 2; i <= Math.sqrt(n); i++)
            if (n % i == 0) 
                return false;

        // If no divisors were found, n is prime
        return true;
    }

    public static void main(String[] args) {
        int n = 11;
      	if(isPrime(n)){
        	System.out.println("true");
        }else{
          System.out.println("false");
    	}
    }
}
Python
import math

def isPrime(n):

    # Numbers less than or equal to 1 are not prime
    if n <= 1:
        return False

    # Check divisibility from 2 to the square root of n
    for i in range(2, int(math.sqrt(n)) + 1):
        if n % i == 0:  
            return False

    # If no divisors were found, n is prime
    return True
  
if __name__ == "__main__":
  n = 11 
  if(isPrime(n)): 
    print("true")
  else:
    print("false")
C#
using System;

class GfG {
    static bool IsPrime(int n) {

        // Numbers less than or equal to 1 are not prime
        if (n <= 1)
            return false;

        // Check divisibility from 2 to the square root of n
        for (int i = 2; i <= Math.Sqrt(n); i++)
            if (n % i == 0)  
                return false;

        // If no divisors were found, n is prime
        return true;
    }

    static void Main(string[] args) {
        int n = 11;
      	if(IsPrime(n))
           Console.WriteLine("true");
      	else
          Console.WriteLine("false");
    }
}
Javascript
// Function to check whether a number is prime or not
function isPrime(n) {

    // Numbers less than or equal to 1 are not prime
    if (n <= 1)
        return false;

    // Check divisibility from 2 to the square root of n
    for (let i = 2; i <= Math.sqrt(n); i++)
        if (n % i === 0) 
            return false;

    // If no divisors were found, n is prime
    return true;
}

// Driver Code
let n = 11; 
if(isPrime(n))
	console.log("true");
else
	console.log("false");

Output
true

Time Complexity: O(sqrt(n))
Auxiliary Space: O(1)

[Expected Approach - 2] Optimized Trial Division Method - O(√n) Time and O(1) Space

We know that any integer number can be written in the form of 6k+i, where k is a nonnegative integer (like 0, 1, 2, 3,...) and i is a number between 0 and 5 (so i can be 0, 1, 2, 3, 4, or 5). If we look closely, we’ll notice that when i is 0, 2, 3, or 4, the numbers 6k, 6k+2, 6k+3, and 6k+4 are all divisible by either 2 or 3. But prime numbers greater than 3 can't be divisible by 2 or 3. Therefore, the only forms left that a prime number can have are 6k+1 or 6k+5 (since these forms are not divisible by 2 or 3).

Instead of checking every number up to the √n to see if it divides n, we only check numbers of the form 6k+1 and 6k+5. This reduces the number of checks needed.

C++
#include <iostream>
#include <cmath>
using namespace std;

bool isPrime(int n) {
  
    // Check if n is 1 or 0
    if (n <= 1)
        return false;

    // Check if n is 2 or 3
    if (n == 2 || n == 3)
        return true;

    // Check whether n is divisible by 2 or 3
    if (n % 2 == 0 || n % 3 == 0)
        return false;
    
    // Check from 5 to square root of n
    // Iterate i by (i+6)
    for (int i = 5; i <= sqrt(n); i = i + 6)
        if (n % i == 0 || n % (i + 2) == 0)
            return false;

    return true;
}

int main() {
    int n = 11;  
  	if(isPrime) cout << "true";
  	else cout<<"false";
    return 0;
}
C
#include <stdio.h>
#include <stdbool.h>
#include <math.h>

bool isPrime(int n) {
  
    // Check if n is 1 or 0
    if (n <= 1)
        return false;

    // Check if n is 2 or 3
    if (n == 2 || n == 3)
        return true;

    // Check whether n is divisible by 2 or 3
    if (n % 2 == 0 || n % 3 == 0)
        return false;
    
    // Check from 5 to square root of n
    // Iterate i by (i+6)
    for (int i = 5; i <= sqrt(n); i = i + 6)
        if (n % i == 0 || n % (i + 2) == 0)
            return false;

    return true;
}

int main() {
    int n = 11;  
    if( isPrime(n)) printf("%s","true");
  	else printf("%s","false");
    return 0;
}
Java
class GfG {
    static boolean isPrime(int n) {
      
        // Check if n is 1 or 0
        if (n <= 1)
            return false;

        // Check if n is 2 or 3
        if (n == 2 || n == 3)
            return true;

        // Check whether n is divisible by 2 or 3
        if (n % 2 == 0 || n % 3 == 0)
            return false;
        
        // Check from 5 to square root of n
        // Iterate i by (i+6)
        for (int i = 5; i <= Math.sqrt(n); i = i + 6)
            if (n % i == 0 || n % (i + 2) == 0)
                return false;

        return true;
    }

    public static void main(String[] args) {
        int n = 11; 
      	if(isPrime(n)){
        	System.out.println("true");
        }else{
          System.out.println("false");
    	}
    }
}
Python
import math

def isPrime(n):

    # Check if n is 1 or 0
    if n <= 1:
        return False

    # Check if n is 2 or 3
    if n == 2 or n == 3:
        return True

    # Check whether n is divisible by 2 or 3
    if n % 2 == 0 or n % 3 == 0:
        return False
    
    # Check from 5 to square root of n
    # Iterate i by (i+6)
    i = 5
    while i <= math.sqrt(n):
        if n % i == 0 or n % (i + 2) == 0:
            return False
        i += 6

    return True

if __name__ == "__main__":
  n = 11
  if(isPrime(n)): 
    print("true")
  else:
    print("false")
C#
using System;

class GfG {
    static bool IsPrime(int n) {
      
        // Check if n is 1 or 0
        if (n <= 1)
            return false;

        // Check if n is 2 or 3
        if (n == 2 || n == 3)
            return true;

        // Check whether n is divisible by 2 or 3
        if (n % 2 == 0 || n % 3 == 0)
            return false;
        
        // Check from 5 to square root of n
        // Iterate i by (i+6)
        for (int i = 5; i <= Math.Sqrt(n); i += 6)
            if (n % i == 0 || n % (i + 2) == 0)
                return false;

        return true;
    }

    static void Main(string[] args) {
        int n = 11;  
      	if(IsPrime(n))
           Console.WriteLine("true");
      	else
          Console.WriteLine("false");
    }
}
Javascript
function isPrime(n) {
    // Check if n is 1 or 0
    if (n <= 1)
        return false;

    // Check if n is 2 or 3
    if (n === 2 || n === 3)
        return true;

    // Check whether n is divisible by 2 or 3
    if (n % 2 === 0 || n % 3 === 0)
        return false;
    
    // Check from 5 to square root of n
    // Iterate i by (i+6)
    for (let i = 5; i <= Math.sqrt(n); i += 6)
        if (n % i === 0 || n % (i + 2) === 0)
            return false;

    return true;
}

// Driver Code
let n = 11;
if(isPrime(n))
	console.log("true");
else
	console.log("false");

Output
true

Time Complexity: O(sqrt(n))
Auxiliary Space: O(1)

Primality Testing Methods

Sieve Algorithms for Prime Number Generation

For more related article on Sieve algorithms , please refer to Recent Articles on Sieve

For more related problems on prime number, please refer toRecent Articles on Prime Numbers


Similar Reads

three90RightbarBannerImg