Java program to check prime number - LearnHowToCode SarkariResult.com Interview Questions and Answers LearnHowToCodeOnline
Java program to check prime number

Java program to check prime number

Java program to check prime number

The number which is only divisible by itself and 1 is known as prime number, for example 7 is a prime number because it is only divisible by itself and 1.
This program takes the number (entered by user) and then checks whether the input number is prime or not. The program then displays the result. If you are looking for a program that displays the prime number between two intervals t 

Example: Program to check whether input number is prime or not

To understand this program you should have the knowledge of for loopif-else statements and break statement.
import java.util.Scanner;
class PrimeCheck
{
   public static void main(String args[])
   {  
 int temp;
 boolean isPrime=true;
 Scanner scan= new Scanner(System.in);
 System.out.println("Enter any number:");
 //capture the input in an integer
 int num=scan.nextInt();
        scan.close();
 for(int i=2;i<=num/2;i++)
 {
           temp=num%i;
    if(temp==0)
    {
       isPrime=false;
       break;
    }
 }
 //If isPrime is true then the number is prime else not
 if(isPrime)
    System.out.println(num + " is a Prime Number");
 else
    System.out.println(num + " is not a Prime Number");
   }
}
Output:
Enter any number:
19
19 is a Prime Number
Output 2:
Enter any number:
6
6 is not a Prime Number
You can also use while loop to check the prime number:
Just replace this part of the code in above program:
for(int i=2;i<=num/2;i++)
{
   temp=num%i;
   if(temp==0)
   {
      isPrime=false;
      break;
   }
}
with this:
int i=2;
while(i<= num/2)
{
   if(num % i == 0)
   {
 isPrime = false;
 break;
   }
   i++;
}

About Mariano

I'm Ethan Mariano a software engineer by profession and reader/writter by passion.I have good understanding and knowledge of AngularJS, Database, javascript, web development, digital marketing and exploring other technologies related to Software development.

0 comments:

Featured post

Political Full Forms List

Acronym Full Form MLA Member of Legislative Assembly RSS Really Simple Syndication, Rashtriya Swayamsevak Sangh UNESCO United Nations E...

Powered by Blogger.