Sunday, 7 February 2016

Write a program to closest prime number to any input number ?

package test;
import java.util.*;

public class closestprime {
public static boolean isprime(int a)
{int c=0;
for(int i=2;i<a/2;i++)
{
if(a%i==0)
{
c=1;
}
}

if(c==1)
         return false;
else
return true;


}

public static void main(String[] arg)
{
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int i;
int n,n1,d,d1;
for(i=a+1;;i++)
{
if(isprime(i))
{    n=i;
    d=i-a;

break;
}
}
for(i=a-1;;i--)
{
if(isprime(i))
{    d1=a-i;
n1=i;

break;
}
}
if(d>d1)
System.out.println("closest prime no.: "+n1);
else if(d1>d)
System.out.println("closest prime no.: "+n);
else
System.out.println("closest prime no.: "+n+" "+n1);
}

}

2 comments:

  1. You are on your way to find the gifts. All the gifts lie in your path in a straight line at prime numbers and your house is at 0.
    Given your current position find the closest gift to your position, and calculate the distance between your current position and gift and tell the distance.

    ReplyDelete