In this article, we will write a java program which checks if the number given as input to the Program is Prime Number or Not.
Method 1: Simpler to Understand
import java.util.Scanner;
public class CheckPrime
{
public static void main(String args[])
{
boolean isPrime=true;
Scanner sc= new Scanner(System.in);
System.out.println("Enter any number:");
//Take the input from user
int num=sc.nextInt();
if(num<=1){
isPrime=false;
}else{
for(int i=2;i
Method 2: Optimized Code
import java.util.Scanner;
public class CheckPrime
{
public static void main(String args[])
{
boolean isPrime=true;
Scanner sc= new Scanner(System.in);
System.out.println("Enter any number:");
//Take the input from user
int num=sc.nextInt();
int sqrt = (int) Math.sqrt(num) + 1;
if(num<=1){
isPrime=false;
}else{
// here the loop iterates only upto the square root of the Number.
// As all remaining iterations are useless.
for(int i=2;i
Output:
$javac CheckPrime.java
$java CheckPrime
Enter any number: 23
23 is a Prime Number
Similar Posts: