Prime Checker

  • + 3 comments

    Hi there, maybe eliminating those who can be divided by 2 will be better?

    after checking if n == 2, we can examine from 3, and 4, 6, 8, 10, ... are not needed.

    (n could be divided by 2 if it can be divided by 4, 6, 8, 10, ...)

    Since then, we could increase our count by 2.

    boolean isPrime(int n){
        if (n == 2)
            return true;
        if (n < 2 || n % 2 == 0) 
            return false;
        for (int i = 3; i <= (int) Math.sqrt(n); i += 2){
            if (n % i == 0)
                return false;
        }
        return true;
    }