In this article we will learn how to find Prime Number Program in Java.
Prime Number : Prime number is a number that is greater than 1 and divided by 1 or itself only. In simple words, prime numbers can’t be divided by other numbers than itself or 1. For example 2, 3, 5, 7, 11…. are the prime numbers.
Code for Prime Number Program in Java
Example 1: Find Prime number using for loop.
[php]
import java.util.Scanner;
class PrimeNumberProgramExample
{
public static void main(String args[])
{
int num,count=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter an Integer number:");
//The input provided by user is stored in num
num=sc.nextInt();
for(int i=1;i<=num;i++){
if(num%i==0){
count++;//increment
}
}
if(count==2){
System.out.print(num+" is a prime number");
}
else{
System.out.print(num+" is not a prime number");
}
}
}
[/php]
Output
Example 2: Find Prime number using While loop.
[php]
import java.util.Scanner;
class PrimeNumberProgramExample
{
public static void main(String args[])
{
int num,count=0,i=1;
Scanner sc=new Scanner(System.in);
System.out.println("Enter an Integer number:");
//The input provided by user is stored in num
num=sc.nextInt();
while(i<=num){
if(num%i==0){
count++;//increment
}
i++;
}
if(count==2){
System.out.print(num+" is a prime number");
}
else{
System.out.print(num+" is not a prime number");
}
}
}
[/php]
Output