In this BlueJ program user will enter any number and the nearest prime number of the entered value will be displayed.
import java.io.*;
class Prime
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n;
public void takeNumber() throws Exception
{
System.out.println("Enter the number:");
n=Integer.parseInt(br.readLine());
System.out.print("Nearest Prime Number of "+n + "=");
while(true)
{
if(prime(n))
{
System.out.print(n);
break;
}
n--;
}
}
private boolean prime(int x)
{
int j;
for(j=2;j< x;i++)
{
{
if(x%j==0)
break;
}
if(j==x)
return true;
else
return false;
}
public static void main(String args[]) throws Exception
{
Prime ob=new Prime();
ob.takeNumber();
}
}
Sample input and output of the program
Sample Input: 25
Sample Output: Nearest Prime number is 23
No comments:
Post a Comment