Is Number Prime

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 19, Windows 10
Language: Java
// Check if number "n" is prime and return true or false.
public static 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;
}

Posted: March 20, 2023

Return to the snippets listing