If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To check if a given number is a prime number in Java, you can use a loop to test whether the number is divisible by any integer between 2 and the square root of the number (inclusive). If the number has no divisors other than 1 and itself, it is considered a prime number. Here's a Java program to check if a given number is prime:
javaCopy code
import java.util.Scanner;
public class PrimeChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int number = scanner.nextInt();
boolean isPrime = checkPrime(number);
if (isPrime) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}
scanner.close();
}
// Function to check if a number is prime
public static boolean checkPrime(int number) {
if (number <= 1) {
return false;
}
// Check for divisors from 2 up to the square root of the number
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
Example output:
lessCopy code
Enter a positive integer: 17
17 is a prime number.
lessCopy code
Enter a positive integer: 20
20 is not a prime number.
In the program above, we take the user input for the number and store it in the variable number
. We call the checkPrime
function to check whether the number is prime or not. The checkPrime
function first handles the base cases: if the number is less than or equal to 1, it returns false
since numbers less than 2 are not prime.
Then, using a for
loop, the function checks for divisors of the number from 2 up to the square root of the number. If the number is divisible by any integer within this range, it is not prime, and the function returns false
. If no divisors are found, the number is prime, and the function returns true
.
The program then prints the result of whether the number is prime or not to the console.
Start the conversation!
Be the first to share your thoughts
Quick answers to common questions about our courses, quizzes, and learning platform