Prime Number Check in Java: Explanation & Practice
Check if a number is prime
Problem summary
Write a program that checks if a given number is prime. Your code should work for ANY positive integer.
Starter code
public class Main {
public static void main(String[] args) {
int number = 17; // Test case 1
// Check if number is prime
// Print: Is prime: <true/false>
}
}Expected output and test cases
- 17 is prime
Is prime: true
- 18 is not prime
Is prime: false
- 1 is not prime
Is prime: false
Hints
- A prime has exactly 2 factors: 1 and itself
- Check divisibility from 2 to sqrt(n)
- 1 is NOT a prime number
Related Control Flow exercises
- Practice Print Even Numbers in Java
- Practice Multiplication Table in Java
- Practice Nth Fibonacci Number in Java
Practice all Control Flow exercises · Run this idea in the Java compiler