Ad space (banner)
โ˜•Java Lessons
Lesson 60 / 68

Checking Whether a Number Is Prime

This lesson covers checking whether a number is prime in Java, so you understand a basic math algorithm using a loop. It's for anyone searching "Java prime check implementation."

Whether a number is prime (divisible only by 1 and itself) can be determined by checking whether it's divisible by any number from 2 up to its square root. If none of them divide it evenly, it's prime.

The example loops over the range for (int i = 2; i * i <= n; i++), deciding the number isn't prime the moment it finds an i where n % i == 0. Checking only up to the square root works because any larger factor would necessarily be paired with a smaller one you'd have already found.

A common early mistake is not knowing why checking only up to the square root is sufficient. Simply checking every number less than n also works correctly, but limiting it to the square root cuts down wasted calculation and speeds things up.

It's an important mathematical property that underlies cryptography too, and there's also a more advanced technique, the Sieve of Eratosthenes, for efficiently finding many primes at once.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Java directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)