Minimize count of given operations required to be performed to make all array elements equal to 1 | Function to check if all array elements are equal or not ; Traverse the array ; If all array elements are not equal ; Function to find minimum count of operation to make all the array elements equal to 1 ; Stores largest element of the array ; Check if a number is a power of 2 or not ; If Max is a power of 2 and all array elements are equal ; Driver Code
function CheckAllEqual ( arr , N ) { for ( i = 1 ; i < N ; i ++ ) { if ( arr [ 0 ] != arr [ i ] ) { return false ; } } return true ; } function minCntOperations ( arr , N ) { var Max = Math . max . apply ( Math , arr ) ; var isPower2 ; if ( parseInt ( ( Math . ceil ( ( Math . log ( N ) / Math . log ( N ) ) ) ) ) == parseInt ( ( Math . floor ( ( ( Math . log ( N ) / Math . log ( 2 ) ) ) ) ) ) ) { isPower2 = true ; } else { isPower2 = false ; } if ( isPower2 && CheckAllEqual ( arr , N ) ) { return parseInt ( ( Math . log ( Max ) / Math . log ( 2 ) ) ) ; } else { return parseInt ( Math . ceil ( Math . log ( Max ) / Math . log ( 2 ) ) ) + 1 ; } } var arr = [ 2 , 4 ] ; var N = arr . length ; document . write ( minCntOperations ( arr , N ) ) ;