Advertisement
Guest User

Find Nearest Prime

a guest
Aug 24th, 2016
1,914
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.62 KB | None | 0 0
  1. import java.util.*;
  2. public class NearestPrime
  3. {
  4.     public static boolean isPrime(int n)//Function to check if a number is Prime.
  5.     {
  6.         int c=0;
  7.         for(int i=1;i<=n;i++)
  8.         {
  9.             if(n%i==0)
  10.                 c++;
  11.         }
  12.         if(c==2)//Prime no.has 2 factors-1 and number itself.
  13.             return true;
  14.         else
  15.             return false;
  16.     }
  17.  
  18.     public static void main(String args[])
  19.     {
  20.         Scanner ob=new Scanner(System.in);
  21.         System.out.println("Enter number whose nearest prime is to be found.");
  22.         int num=ob.nextInt();
  23.         int diff1=0,diff2=0;
  24.         int num1=0,num2=0;
  25.         for(int i=num;;i++)//No end limit as when prime will be found we will break the loop.
  26.         {
  27.             if(isPrime(i))
  28.             {
  29.                 diff1=i-num;
  30.                 num1=i;
  31.                 break;
  32.             }
  33.         }
  34.         for(int i=num;;i--)//No end limit as when prime will be found we will break the loop.
  35.         {
  36.             if(isPrime(i))
  37.             {
  38.                 diff2=num-i;
  39.                 num2=i;
  40.                 break;
  41.             }
  42.         }
  43.         if(diff1<diff2)//Nearest Prime number will have least difference from given number.
  44.             System.out.println("Nearest Prime Number from "+num+" is "+num1);
  45.         else if(diff2<diff1)
  46.             System.out.println("Nearest Prime Number from "+num+" is "+num2);
  47.             else//There can be more than 1 nearest prime like for 6 we have 5 and 7 as nearest prime.
  48.             System.out.println("Nearest Prime Number from "+num+" is "+num2+" and "+num1);
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement