Is Number Prime in Java

Description: Checks to see if a supplied integer is prime or not in Java using a for loop that checks all odd numbers up to the square root of the supplied number.
Tested Platform: Java SE 7, Windows 7
Language: Java
// Check if number "n" is prime and return true or false.
boolean isPrime(int n) {

    // If number is divisible by 2 we know it is not prime.
    if ((n%2) == 0) return false;

    // Check odd numbers
    for (int i = 3; i*i <= n; i += 2) {
        if ((n%i) == 0) {  return false; }
    }

    return true;
}

Submitted: August 30, 2013

Return to the snippets listing