Java Program to Check Whether Given Number is Prime or Not using Scanner

Share

The program takes input from the use and finds whether the given input is a prime number or not.  A prime number is a number which has exactly two factors 1 and the number itself. For example, 5,7,11….

Approach to check a given number is prime or not:

  • If a number is divisible by 1 or itself then only , the number would be considered as prime, otherwise not
  • Execute a loop body until it reaches to the middle of the target number because the number afterwards always generate multiples that would be greater than target number. i.e 6 is the number, its half would be 3. After 3, 4 would always give greater number than 6, such as 8,12,16,20.

Java program to check whether a number is prime or not using Scanner

Program:

import java.util.Scanner;

public class PrimeOrNot{

public static void main(String[] args) {
int num,i,flag=0;
System.out.print("Please enter a number = ");
Scanner ed = new Scanner(System.in);
num= ed.nextInt();
for(i=2;i<= num/2;i++)
{
if(num%i==0) 
{
flag=1;
break;
}
}
if(num==2)
System.out.println(num+" is an even prime number . ");
else if(num==1)
System.out.println(num+" isn't a prime or composite number . ");
else if(flag==1)
System.out.println(num+" isn't prime number . ");
else
System.out.println(num+" is a prime number . "); 
}

}

Prime Number Program Using While Loop

public static void main(String[] args) {
       int num, i=2, flag = 0;
       System.out.print("Please enter a number = ");
       Scanner ed = new Scanner(System.in);
       num = ed.nextInt();
       while (i <= num / 2) {
           if (num % i == 0) {
               flag = 1;
               break;
           }
           i++;
       }
       if (num == 2) System.out.println(num + " is an even prime number . ");
       else if (num == 1) System.out.println(num + " isn't a prime or composite number . ");
       else if (flag == 1) System.out.println(num + " isn't prime number . ");
       else System.out.println(num + " is a prime number . ");
   }

Output:

Please enter a number = 131
131 is a prime number

This post was last modified on December 27, 2020

Sandeep Verma

Published by
Sandeep Verma
Tags: Check Whether Given Number is Prime or Not java java program Java Program to Check Whether Given Number is Prime or Not Java Program to Check Whether Given Number is Prime or Not using Scanner Prime Number Program Prime Number Program in Java