Minimum operations required to make every element greater than or equal to K | Function to calculate gcd of two numbers ; function to get minimum operation needed ; The priority queue holds a minimum element in the top position ; push value one by one from the given array ; store count of minimum operation needed ; All elements are now >= k ; It is impossible to make as there are no sufficient elements available ; Take two smallest elements and replace them by their LCM first smallest element ; Second smallest element ; Increment the count ; Driver code
function gcd ( a , b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } function FindMinOperation ( a , n , k ) { let Q = [ ] ; for ( let i = 0 ; i < n ; i ++ ) Q . push ( a [ i ] ) ; Q . sort ( function ( a , b ) { return a - b } ) ; let ans = 0 ; while ( true ) { if ( Q [ 0 ] >= k ) break ; if ( Q . length < 2 ) return - 1 ; let x = Q [ 0 ] ; Q . shift ( ) ; let y = Q [ 0 ] ; Q . shift ( ) ; let z = parseInt ( ( x * y ) / gcd ( x , y ) , 10 ) ; Q . push ( z ) ; Q . sort ( function ( a , b ) { return a - b } ) ; ans ++ ; } return ans ; } let a = [ 3 , 5 , 7 , 6 , 8 ] ; let k = 8 ; let n = a . length ; document . write ( FindMinOperation ( a , n , k ) ) ;