Nearest prime pair number in java - Program to print the nearest prime for a given number
In the following program, it generates a nearest prime number of a given
number. This program takes a number in the main() method and then it passed to a
for loop and from there it checks the prime number with its closest. Suppose when
we enter 15 it will print the nearest prime pair number as follows:
11, 13, and 17, 19.
import java.util.*;
class NearestPrimeNumber
{
public boolean isPrime(int number)
{
int i,flag = 1;
for(i=2;i<number;i++)
{
if(number % i==0)
{
flag = 0;
break;
}
}
if(flag == 1)
{
return(true);
}
else
return(false);
}
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
NearestPrimeNumber ob=new NearestPrimeNumber();
int i,m,num,temp = 0;
System.out.println("Enter a number");
num=in.nextInt();
for(i=num-1;i>=1;i--)
{
if(ob.isPrime(i))
{
temp = i + 2;
if(ob.isPrime(temp))
{
System.out.println("nearest prime pair is");
System.out.println(i + " , "+ temp);
break;
}
}
}
for(i=num ; ; i++)
{
if(ob.isPrime(i))
{
m=i-2;
if(ob.isPrime(m))
{
if(temp != i)
{
System.out.println(m+" , "+i);
break;
}
else
{
break;
}
}
}
}
}
}
More Java program