# Write a Java program to check if the number entered by the user is Prime number or not.
Algorithm
- Start
- x:=0
- If x<=1, go to step 4 or else go to step 8
- Print "Enter a number"
- Read x
- If x<=1, go to step 7 or else go to step 8
- Print "Invalid Input. Try Again".
- count:=0
- i:=2
- If i<x, go to step 11 or else go to step 14
- If x%i==0, go to step 12 or else go to step 13
- count ++
- i++. Go to step 10.
- If count>0, go to step 15 or else go to step 16
- Print "The given number is not a prime number". Go to step 17
- Print "The given number is a prime number"
- Stop
Program
Buffered Reader
import java.io.*;
class Prime
{
int x;
void accept() throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(x<=1)
{
System.out.println("Enter a number");
x=Integer.parseInt(br.readLine());
if(x<=1)
{
System.out.println("Invalid Input. Try Again.");
}
}
}
boolean checkPrime()
{
int count = 0;
for(int i=2;i<x;i++)
{
if(x%i==0)
{
count++;
}
}
if (count > 0)
{
return false;
}
else
{
return true;
}
}
void displayt()
{
System.out.println("The given number is a prime number");
}
void displayf()
{
System.out.println("The given number is not a prime number");
}
void main() throws IOException
{
accept();
if(checkPrime()==true)
{
displayt();
}
else
{
displayf();
}
}
}
Scanner
import java.util.*;
class Prime
{
int x;
void accept()
{
Scanner sc=new Scanner(System.in);
while(x<=1)
{
System.out.println("Enter a number");
x=sc.nextInt();
if(x<=1)
{
System.out.println("Invalid Input. Try Again.");
}
}
}
boolean checkPrime()
{
int count = 0;
for(int i=2;i<x;i++)
{
if(x%i==0)
{
count++;
}
}
if (count > 0)
{
return false;
}
else
{
return true;
}
}
void displayt()
{
System.out.println("The given number is a prime number");
}
void displayf()
{
System.out.println("The given number is not a prime number");
}
void main()
{
accept();
if(checkPrime()==true)
{
displayt();
}
else
{
displayf();
}
}
}
Documentation
Variable Description
Data Type | Variable Name | Description |
int | x | Accept a value from the user/ |
int | i | Acts as a counter variable |
int | count | Counts the number of factors of a number except 1 and itself. |
Method Description
Return Type | Function Name | Description |
void | accept() | Accepts a value from the user |
boolean | checkPrime() | Checks if the given number is prime or not. |
void | displayt() | Displays the message if the condition is true |
void | displayf() | Displays the message if the condition is false |
void | main() | Acts as an execution gateway to the program |
Output:
Share with all ISC Computer Science Students you know.
Comment below with all your program requests and blog suggestions.
Follow us on social media by clicking on these links.
Instagram : @IscJavaCode
Twitter: @IscCode
Quora: ISC Java Code
Stay Healthy
Stay Happy
Stay Helpful
Comments
Post a Comment