Java Program to check the given number is prime or not.
Objective
Write a Java program to determine whether a given positive integer is a prime number.
Algorithm / Approach
- Read an integer
nfrom the user. - Initialize a
flagvariable to 0. - Run a loop from
i = 2up to the square root ofn. - Inside the loop, check if
nis perfectly divisible byi(n % i == 0). - If divisible, set
flag = 1and immediatelybreakout of the loop. - After the loop, if
flag == 0, the number is prime; otherwise, it is not prime.
Test.java
import java.util.Scanner;
class Test {
public static void main(String[] a)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter a num: ");
int n = s.nextInt();
int flag = 0;
for(int i =2; i<=Math.sqrt(n);i++){
if(n%i==0) {
flag = 1;
break;
}
}
if(flag==0) {
System.out.print(n+" is a prime no.");
}
else {
System.out.print(n+" is not a prime no.");
}
}
}
Expected Output
Enter a num: 45 45 is not a prime no.
Explanation of the Program
- A prime number is only divisible by 1 and itself.
- Instead of checking all numbers up to
n-1, the program optimizes the search by only checking up toMath.sqrt(n). If a number has factors, at least one factor must be less than or equal to its square root. - The
flagvariable acts as a boolean indicator. Once a divisor is found, thebreakstatement stops further unnecessary checks.
Complexity
Time Complexity
O(√n) - Optimized by stopping at the square root.
Space Complexity
O(1)
Common Mistakes
- Checking divisibility up to
ninstead of the square root, which is highly inefficient for very large numbers. - Not handling edge cases like negative numbers, 0, or 1 (which are not prime).