Prime Check in Java
Decide if an integer is prime in Java with an isPrime helper and odd-divisor checks. Use i <= n / i to avoid overflow; one and negatives are rejected.
1import java.util.Scanner;23public class Main {4 private static boolean isPrime(int n) {5 if (n <= 1) return false;6 if (n == 2) return true;7 if (n % 2 == 0) return false;8 for (int i = 3; i <= n / i; i += 2) {9 if (n % i == 0) return false;10 }11 return true;12 }1314 public static void main(String[] args) {15 Scanner sc = new Scanner(System.in);16 System.out.print("Enter a number: ");17 int n = sc.nextInt();1819 if (isPrime(n)) {20 System.out.println(n + " is Prime");21 } else {22 System.out.println(n + " is not Prime");23 }24 sc.close();25 }26}
Sample Output
Enter a number: 29 29 is Prime
For 29, trials 3 and 5 do not divide it. The next odd value is beyond the limit, so the helper accepts it.
In this one
- Handle the special cases 1 and 2
- Search for a divisor efficiently
- Include the exact square-root limit
How it works
- 1
Read n.
- 2
Reject n <= 1 and handle even values.
- 3
Try odd divisors from 3 through the square-root limit.
- 4
Print the message based on the helper result.
Edge cases
Only even prime
Enter 2
The early return accepts it before the even-number rejection.
Odd square
Enter 49
The test with i = 7 finds an exact divisor.
What's going on
Check whether one whole number is prime. A prime is greater than one and has no positive divisors except one and itself. This program is useful for understanding why a number property needs special small cases as well as a general loop.
Scanner is the keyboard reader. The helper rejects n <= 1, accepts 2, and rejects other even numbers. It then checks only odd possible divisors. The % operator gives the remainder after division; a zero result reveals an exact divisor and ends the helper with false.
If no divisor is found through the square-root limit, the helper returns true. The condition i <= n / i tests that limit without risking a too-large i * i product. Do not classify 1 as prime. Also include the equality at the limit, otherwise a square such as 49 can slip through without testing 7.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Is 2 prime?
Pick an answer to check it.
Question 2
What does a zero remainder reveal?
Pick an answer to check it.
Questions people ask
Why is one not prime?
It has only one positive divisor, not two.
Why use n / i in the loop condition?
It represents the same positive-input limit as i * i <= n without multiplying i by itself.
Does finding one divisor finish the check?
Yes. One extra divisor is enough to prove that the number is not prime.