Posts Check Prime
Post
Cancel

Check Prime

Problem Description

Given a number N check if it’s a prime number.

Solution

The main this to remember here is that we need to check only till square root of N, because if i is a factor of N, N/i will also be a factor of N. If we get any 1 factor, return false.

1
2
3
4
5
6
7
8
9
10
static boolean isPrime(int n){

    for(int i=2; i*i<=n; i++){  //We can check till root N only. If i is a factor, N/i will also be a factor.
        if(n%i == 0){
            return false;
        }
    }

    return true;
}
This post is licensed under CC BY 4.0 by the author.