Prime Number Program in Java – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Sun, 27 Dec 2020 12:07:42 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg Prime Number Program in Java – Programmerbay https://programmerbay.com 32 32 Java Program to Check Whether Given Number is Prime or Not using Scanner https://programmerbay.com/java-program-to-check-whether-given-number-is-prime-or-not-using-scanner/ https://programmerbay.com/java-program-to-check-whether-given-number-is-prime-or-not-using-scanner/#respond Tue, 07 Jul 2020 06:49:13 +0000 https://www.programmerbay.com/?p=4150 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

]]>
https://programmerbay.com/java-program-to-check-whether-given-number-is-prime-or-not-using-scanner/feed/ 0