Flash cards
Review the key moves
What is the main idea behind Java How To - Check if a Number Is Prime?
Lesson checks
Practice each idea before moving on
Short Mimo-style checks built from this lesson's code, terms, and sequence.
Which statement best captures the main point of this lesson?
Complete the missing token from the example code.
___ n = 29; // Number used to checkPut the learning moves in the order that makes the concept easiest to apply.
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.