Minimum prime numbers required to be subtracted to make all array elements equal | Javascript program for the above approach ; Stores the sieve of prime numbers ; Function that performs the Sieve of Eratosthenes ; Iterate over the range [ 2 , 1000 ] ; If the current element is a prime number ; Mark all its multiples as false ; Function to find the minimum number of subtraction of primes numbers required to make all array elements the same ; Perform sieve of eratosthenes ; Find the minimum value ; Stores the value to each array element should be reduced ; If an element exists with value ( M + 1 ) ; Stores the minimum count of subtraction of prime numbers ; Traverse the array ; If D is equal to 0 ; If D is a prime number ; Increase count by 1 ; If D is an even number ; Increase count by 2 ; If D - 2 is prime ; Increase count by 2 ; Otherwise , increase count by 3 ; Driver Code
var limit = 100000 ; var prime = Array ( limit + 1 ) . fill ( true ) ; function sieve ( ) { for ( p = 2 ; p * p <= limit ; p ++ ) { if ( prime [ p ] == true ) { for ( i = p * p ; i <= limit ; i += p ) prime [ i ] = false ; } } } function findOperations ( arr , n ) { sieve ( ) ; var minm = Number . MAX_VALUE ; for ( i = 0 ; i < n ; i ++ ) { minm = Math . min ( minm , arr [ i ] ) ; } var val = minm ; for ( i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == minm + 1 ) { val = minm - 2 ; break ; } } var cnt = 0 ; for ( i = 0 ; i < n ; i ++ ) { var D = arr [ i ] - val ; if ( D == 0 ) { continue ; } else if ( prime [ D ] == true ) { cnt += 1 ; } else if ( D % 2 == 0 ) { cnt += 2 ; } else { if ( prime [ D - 2 ] == true ) { cnt += 2 ; } else { cnt += 3 ; } } } return cnt ; } var arr = [ 7 , 10 , 4 , 5 ] ; var N = 4 ; document . write ( findOperations ( arr , N ) ) ;