How can we write a Java program to determine whether an input positive integer is prime?
To write a Java program that determines whether an input positive integer is prime, we can follow the steps below. Let's walk through the explanation and code snippet provided.
Understanding Prime Numbers:
Prime numbers are positive integers that have exactly two distinct factors - 1 and the number itself. For example, 2, 3, 5, 7 are prime numbers as they can only be divided by 1 and the number itself.
Java Program to Determine Prime Number:
To determine whether an input positive integer is prime, we can use the following Java program:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int num = input.nextInt();
boolean isPrime = true;
if (num <= 1) {
isPrime = false;
} else {
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime) {
System.out.println(num + " is prime");
} else {
System.out.println(num + " is not prime");
}
}
}
Explanation of the Program:
- We first prompt the user to enter a positive integer using the Scanner class.
- We initialize a boolean variable 'isPrime' to true, which we will use to determine whether the number is prime or not.
- If the input number is less than or equal to 1, it is not prime.
- We then loop through numbers from 2 to the square root of the input number. If the input number is divisible by any of these numbers, it is not prime.
- If the loop completes without finding a factor, the number is prime, and we print a message indicating that the input number is prime.
I hope this explanation helps in understanding how to write a Java program to determine whether an input positive integer is prime.