Java Code for Prime Number

A prime number is a natural number greater than 1, that’s not divisible by any other number. In simple terms a prime number has only two positive divisors 1 and itself for example 2,3,5,7—– are prime numbers. Natural numbers other than prime numbers are known as composite numbers.

Java Code for Prime Number

Lets see the Java code for prime number. There are many different ways to write code to check whether a given number is a prime number or not. The simplest approach for checking prime numbers is to use a loop to iterate through all the numbers from 2 to the square root of the number. If any of those numbers divide the given number into two equal parts then the given number is not a prime number. Otherwise, it is a prime number.

package gangforcode;
import java.util.Scanner;

public class Prime {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number");
        int n = sc.nextInt();
        if(n<2){
            System.out.println("Not Prime");
        }
        else{
            boolean isPrime = true;
            for(int i=2;i<=Math.sqrt(n);i++){
                if(n%i==0){
                    isPrime=false;
                    break;
                }
            }

            if(isPrime)
                System.out.println("Prime Number");
            else System.out.println("Not Prime");
        }

    }
}

Output

Java code for prime number

Even though this is the simplest approach for checking prime numbers but, it can be slow for large numbers. The more efficient approach to check prime numbers is the Sieve of Eratosthenes. Sieve of Eratosthenes is a simple algorithm for finding all the prime numbers in the given range.

See Also

Leave a Comment