Prime Number Program in Java
Written by
In the following question, we are supposed to write a Java Source Code to ask the user for an Integer input and check if the number is a Prime Number.
Prime number are those numbers who have only two factors: 1 and the number itself.
Example: 1,2,3,5,7,11,13,etc are some examples of Prime Number.
The standard algorithm will be:
- Enter and Store the Integer Input from the user.
- Run a For-Loop from 1 to N.
- At every iteration of the loop, check if the value of the iteration completely divides the integer input.
- If the result is true, the counter variable is incremented.
- After the loop terminates, check if the value of the counter variable is 2 or not, which means there are only two factors for the N.
- Print the Result accordingly.
Source Code:
/* Program to check if a number is Prime or Not*/
import java.util.*;
class PrimeNumber
{
public static void main()
{
Scanner inp=new Scanner(System.in);
System.out.print("\n Enter Number: ");
int n=inp.nextInt();
int i,c=0;
for(i=1;i<=n;i++)
{
if(n%i==0) //Checking if there are two factors of the number.
c++;
}
if(c==2)
System.out.println(n+" is a Prime Number");
else
System.out.println(n+" is not a Prime Number");
}
}
Output:
Enter Number: 2
2 is a Prime Number
Enter Number: 36
36 is not a Prime Number
Enter Number: 101
101 is a Prime Number