The Prime Number Program in Java is a simple yet essential program that determines whether a given number is prime or not.
What is a Prime Number ?
A prime number is a positive number greater than 1 which is only divisible by 1 and the number itself.
Some examples of prime numbers are : 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47
Steps for Prime Number Program in Java
We will follow the below steps to writing the Prime Number program in Java.
- In this program, the user is prompted to enter a number.
- It iterates from 2 to the square root of the number and checks if any number divides the entered number evenly.
- If a divisor is found, the number is not prime. Otherwise, it is considered prime.
Using For Loop
Java Code Snippet
import java.util.Scanner;
public class PrimeNumberProgram {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
while (!scanner.hasNextInt()) {
System.out.println("Invalid input. Please enter a valid positive integer: ");
scanner.next();
}
int number = scanner.nextInt();
scanner.close();
if (number <= 1) {
System.out.println("The entered number is not a valid candidate for a prime number.");
} else {
boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}
}
}
}
Enter a number: 10
10 is not a prime number.
Using While Loop
Java Code Snippet
import java.util.Scanner;
public class PrimeNumberProgram {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
while (!scanner.hasNextInt()) {
System.out.println("Invalid input. Please enter a valid positive integer: ");
scanner.next();
}
int number = scanner.nextInt();
scanner.close();
if (number <= 1) {
System.out.println("The entered number is not a valid candidate for a prime number.");
} else {
boolean isPrime = true;
int i = 2;
while (i <= Math.sqrt(number)) {
if (number % i == 0) {
isPrime = false;
break;
}
i++;
}
if (isPrime) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}
}
}
}
Output
Enter a number: 11
11 is a prime number.
Conclusion
The Prime Number Program in Java allows users to input a number and determine if it is a prime number or not.
Related Article
Amazing!,
I have suggestion to improve it ,
the input can be checked till (int)Math.sqrt(input)+1 by using number theory
if a number is not divisible by its factors till square root of the number , then the number is prime.
and hence it will improve time complexity from O(n/2)=O(n) to O(n^1/2)