bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths

Loading lesson path

Learn/Java/Java How To's
Java•Java How To's

Java How To - Check if a Number Is Prime

Check if a Number Is Prime

A prime number is only divisible by 1 and itself.

To test if a number is prime, we try dividing it by every number from 2 up to its square root:

Example

int n = 29;  // Number used to check
boolean isPrime = n > 1;
for (int i = 2; i * i <= n; i++) {
  if (n % i == 0) {
    isPrime = false;
    break;
  }
}
System.out.println(n + (isPrime ? " is prime" : " is not prime"));

Explanation: We start with the number 29 . Since 29 is greater than 1, the loop checks if it can be divided evenly by any number from 2 up to the square root of 29 (about 5.38). The numbers 2, 3, 4, and 5 do not divide 29 without a remainder, so the program concludes that 29 is prime.

Previous

Java How To Find the GCD

Next

Java How To Loop Through an ArrayList