bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

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

Java How To - Check if a Number Is Prime

Flash cards

Review the key moves

1/4
Core idea

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.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

___ n = 29; // Number used to check
3Order

Put the learning moves in the order that makes the concept easiest to apply.

To test if a number is prime, we try dividing it by every number from 2 up to its square root:
A prime number is only divisible by 1 and itself.
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