Prime Number Checker in Java
This program checks if a given number is prime. A prime number is a natural number greater than 1 that is not a product of two smaller natural numbers. For example, 5 is prime because the only ways of writing it as a product, 1 × 5 or 5 × 1, involve 5 itself.
Java Program
/**
* This class contains a method to check if a given number is prime.
*/
public class PrimeNumberChecker {
/**
* This method checks if the given number is prime.
*
* @param number The number to check.
* @return true if the number is prime, false otherwise.
*/
public static boolean isPrime(int number) {
// Check if number is less than 2, as prime numbers are greater than 1
if (number < 2) {
return false;
}
// Loop to check if the number has any divisor other than 1 and itself
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
return false; // number is not prime
}
}
return true; // number is prime
}
/**
* Main method to test the isPrime method.
*
* @param args Command line arguments.
*/
public static void main(String[] args) {
int numberToCheck = 29; // Example number to check
if (isPrime(numberToCheck)) {
System.out.println(numberToCheck + " is a prime number.");
} else {
System.out.println(numberToCheck + " is not a prime number.");
}
}
}
Explanation
The isPrime
method works as follows:
- First, it checks if the number is less than 2. If so, it returns
false
because prime numbers are greater than 1. - Next, it loops from 2 to the square root of the number. The reason for checking up to the square root is that if
n = a * b
, then one of the factorsa
orb
must be less than or equal to the square root ofn
. - If the number is divisible by any number in this range, it returns
false
because the number is not prime. - If the loop completes without finding any divisors, the number is prime, and the method returns
true
.
How to Use the Program
- Copy the Code: Copy the Java code provided in the
<code>
tags. - Create a Java File: Create a new file named
PrimeNumberChecker.java
. - Paste the Code: Paste the copied code into the
PrimeNumberChecker.java
file. - Compile the Program: Open a terminal or command prompt, navigate to the directory containing the
PrimeNumberChecker.java
file, and compile the program using the following command:javac PrimeNumberChecker.java
- Run the Program: After compilation, run the program using the following command:
java PrimeNumberChecker
Example Output
For the example number 29
, the program will output:
29 is a prime number.
You can change the value of numberToCheck
in the main
method to test other numbers.