Skip to content
Related Articles
Open in App
Not now

Related Articles

Java program to check if a number is prime or not

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 30 Jan, 2023
Improve Article
Save Article

Given a positive integer, check if the number is prime or not. A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself. Examples of first few prime numbers are {2, 3, 5, Examples :

Input:  n = 11
Output: true

Input:  n = 15
Output: false

Input:  n = 1
Output: false

School Method A simple solution is to iterate through all numbers from 2 to n-1 and for every number check if it divides n. If we find any number that divides, we return false. 

java




// A school method based JAVA program
// to check if a number is prime
class GFG {
 
    static boolean isPrime(int n)
    {
        // Corner case
        if (n <= 1)
            return false;
 
        // Check from 2 to n-1
        for (int i = 2; i < n; i++)
            if (n % i == 0)
                return false;
 
        return true;
    }
 
    // Driver Program
    public static void main(String args[])
    {
        if (isPrime(11))
            System.out.println(" true");
        else
            System.out.println(" false");
        if (isPrime(15))
            System.out.println(" true");
        else
            System.out.println(" false");
    }
}

Output:

true
 false

Time complexity of this solution is O(n) 
Optimized School Method We can do following optimizations:

  1. Instead of checking till n, we can check till √n because a larger factor of n must be a multiple of smaller factor that has been already checked.
  2. The algorithm can be improved further by observing that all primes are of the form 6k ± 1, with the exception of 2 and 3. This is because all integers can be expressed as (6k + i) for some integer k and for i = ?1, 0, 1, 2, 3, or 4; 2 divides (6k + 0), (6k + 2), (6k + 4); and 3 divides (6k + 3). So a more efficient method is to test if n is divisible by 2 or 3, then to check through all the numbers of form 6k ± 1. (Source: wikipedia)

Example : Check number is prime or not using function.

Java




/*package whatever //do not write package name here */
 
import java.io.*;
import java.util.Scanner;
 
class Program
 
{
 
    /*function to check prime or not*/
 
    static void prime(int no)
 
    {
 
        int count = 0;
 
        for (int i = 1; i <= no; i++)
 
        {
 
            if (no % i == 0)
 
                count++;
        }
 
        if (count == 2)
 
            System.out.println(no + " is prime");
 
        else
 
            System.out.println(no + " is not prime");
    }
 
    public static void main(String[] args)
 
    {
 
        prime(13); // calling
 
        prime(20);
 
        prime(23);
    }
}

Output

13 is prime
20 is not prime
23 is prime

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!