How to check prime numbers in Java

Java program to check if a given number is prime or not. This Java method takes an integer n and returns a boolean value. The isPrime method returns true or false depending on whether the number is prime or not. 
public static boolean isPrime(int n) {
    for(int i = 2; i < n; i++) {
        if(n % i == 0) { //if n is divisible by i then n is not prime                                             
            return false;
        }
    }
    return true;
}
A positive integer number is prime if it is only divisible by itself and by 1

The number 5 is a prime number because it can only be divided by itself and by 1. The remainder
5 % 2 = 1
5 % 3 = 2
5 % 4 = 1
5 % 5 = 0

The number 6 is not a prime number because it can be divided by 2:
6 % 2 = 0

This method can be modified to make it faster. It is not necessary to divide by all numbers from 2 to N-1. There are mathematical reasons to prove that N is a prime number if it is not divisible by any integer in the range from 2 to the square root of N.
This is the optimized java code to check if a given number is prime or not:
public static boolean isPrime(int n) {
    for(int i = 2; i < Math.sqrt(n); i++) {
        if(n % i == 0) { //if n is divisible by i then n is not prime                                             
            return false;
        }
    }
    return true;
}

No comments :

Post a Comment