A prime number is a natural number greater than 1 that cannot be made by multiplying two smaller natural numbers. In simpler terms, a prime number can only be divided by 1 and itself without leaving a remainder. Prime numbers are important and interesting in math and computer science.
In this article, we will learn how to write a Java program to check if a given number is a prime number.
Java Program to Check Prime Number
To check if a number is prime, the key idea is to loop through numbers starting from 2 up to the square root of the number. If the number is divisible by any of these, it is not prime. We only check up to the square root because any larger factor would have already been paired with a smaller one that we’ve checked.
Here’s how to write this in Java:
public class Main {
public static void main(String[] args) {
int num = 29;
boolean isPrime = checkPrime(num);
if(isPrime) {
System.out.println(num + " is a prime number.");
} else {
System.out.println(num + " is not a prime number.");
}
}
public static boolean checkPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
In the code above:
- In the main method, we start by setting the number num that we want to check.
- We call the checkPrime method, passing num as the input.
- In the checkPrime method, we first check if num is less than or equal to 1. If it is, the method returns false because numbers less than or equal to 1 are not prime.
- Next, we run a loop that checks every number from 2 up to the square root of num. If num is divisible by any of these, the method returns false because it has a divisor other than 1 and itself.
- If the loop completes without finding a divisor, the method returns true, meaning num is a prime number.
- Back in the main method, we print whether num is a prime number based on the result from the checkPrime method.
If you run this program with num = 29, it will output:
1 | 29 is a prime number. |
If you change num to 15, the output will be:
1 | 15 is not a prime number. |
This simple Java program efficiently checks whether a number is prime by using the mathematical rule that a prime number has no divisors other than 1 and itself.
Conclusion
Writing a Java program to check if a number is prime is a great exercise to build problem-solving skills and understand basic programming concepts. It uses simple math and basic Java structures like loops and conditionals.
We also learned how to make the prime-checking process more efficient by only looping up to the square root of the number. This makes the program run faster, especially for larger numbers.