Facebook
From VENKAT NARASIMAM TENNETI, 1 Year ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 65
  1. /* package codechef; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Codechef
  9. {
  10.         public static void main (String[] args) throws java.lang.Exception
  11.         {
  12.                 // your code goes here
  13.                 Scanner sc=new Scanner(System.in);
  14.                 int test_case=sc.nextInt();
  15.                 while(test_case-- >0){
  16.                     long cupcake=sc.nextLong();
  17.                     if(cupcake>1)
  18.                         System.out.println(maxCupcakes(cupcake));
  19.                     else if(cupcake==1)
  20.                         System.out.println(1);
  21.                     else if(cupcake==0)
  22.                         System.out.println(0);
  23.                 }
  24.         }
  25.         private static long maxCupcakes(long cupcake){
  26.             long result=0;
  27.             long temp=0;
  28.             for(long i=2;i<=cupcake;i++){
  29.                 if(isPrime(i)){
  30.                     temp=cupcake%i;
  31.                 }
  32.                 result=Math.max(temp,result);
  33.             }
  34.             return cupcake-result;
  35.         }
  36.         private static boolean isPrime(long max_num){
  37.            boolean isPrime = true;
  38.            for (long num = 2; num <= max_num; num++)
  39.         {
  40.             for (long i=2; i <= num/2; i++)
  41.             {
  42.                 if ( num % i == 0)
  43.                 {
  44.                     isPrime = false;
  45.                     break;
  46.                 }
  47.             }
  48.         }
  49.         return isPrime;
  50.         }
  51. }