Aquarium

 Coding Problem Keys 

 Aquarium 

 Problem Statement 

An aquarium has N number of cells in it. The number o fish in each cell is represented in the form of Ai of array A, where i represents the i th index of the array A.

Shyam wants to sell the aquarium, but to sell it at a higher price, he will have to make it look better. The aquarium can be made better if in each cell there is a prime number of fish. Shyam can select any index of the array i.e. cell of the aquarium and can add a fish or can remove one fish from the aquarium. Adding or removing a fish takes him one second.

Help out Shyam so that he can make the aquarium better in the last time, and then print that time taken.

 Input Format 

  • The first line contains N (Length of the array)
  • The second line contains N space-separated integers.

 Output Format 

Print an integer denoting the minimum time required.

 Constraints 

1 ≤ N 
 10
 Ai  10000000

 Sample Input 

4
9 5 3 6

 Sample Output 

3

 Explanation 

In sample, two primes 5 and 3 are already present. You don't need to change them. For 9, you can either make 7 or 11, both takes 2 steps.

And, if you can change 6 to either 5 or 7, both takes 1 step. So, as a whole it takes 3 steps to make all elements prime.

 Note: Max Execution Time Limit: 5000 millisecs 

 Solution 

 Programming Language: Java Language 

import java.util.Scanner;
public class Main{
    static boolean isPrime(int x){
        if(x==2 || x==3 || x==5 || x==7) return true;
        else if(x%2==0 || x%3==0 || x%5==0 || x%7==0) return false;
        else if(Math.ceil(Math.sqrt(x))-Math.floor(Math.sqrt(x))==0) return false;
        else return true;
    }
    static int mintime(int A[],int N){
        int sec=0;
        int pnearl=0,pnearh=0;
        for (int i=0;i<N;i++){
            for(int j=A[i];j>=1;j--){
                if(isPrime(j)){
                    pnearl=j;
                    break;
                }
            }
             for(int j=A[i];j<=A[i]+A[i];j++){
                if(isPrime(j)){
                    pnearh=j;
                    break;
                }
            }
            if(A[i]-pnearl < pnearh-A[i]){
                sec+=A[i]-pnearl;
            }else if(A[i]-pnearl > pnearh-A[i]){
                sec+=pnearh-A[i];
            }sec+=pnearh-A[i];
        }return sec;   
    }
    public static void main(String args[]) {
      int N,A[];
      Scanner ip=new Scanner(System.in);
      N=ip.nextInt();
      A=new int[N];
      for(int i=0;i<N;i++)
        A[i]=ip.nextInt();
    System.out.println(mintime(A,N));
    }
}
// Published By PKJCODERS

 (Note: Incase If the code doesn't Pass the output kindly comment us with your feedback to help us improvise.) 

Comments

Popular Posts

Maximum Goods Transported

Mango Distribution

RAT CHEESE MAZE

checkGreatestFactor

Factorials

Reunion