Minimize cost of converting all array elements to Fibonacci Numbers | Function to find the N - th Fibonacci Number ; Find the value of a , b , and r ; Find the N - th Fibonacci ; Return the result ; Function to find the Fibonacci number which is nearest to X ; Calculate the value of n for X ; Return the nearest Fibonacci Number ; Function to find the minimum cost to convert all array elements to Fibonacci Numbers ; Stores the total minimum cost ; Traverse the given array arr [ ] ; Find the nearest Fibonacci Number ; Add the cost ; Return the final cost ; Driver Code
function nthFibo ( n ) { let a = ( Math . pow ( 5 , 0.5 ) + 1 ) / 2 ; let b = ( - 1 * ( Math . pow ( 5 , 0.5 ) ) + 1 ) / 2 ; let r = Math . pow ( 5 , 0.5 ) ; let ans = ( Math . pow ( a , n ) - Math . pow ( b , n ) ) / r ; return Math . floor ( ans ) ; } function nearFibo ( X ) { let a = ( Math . pow ( 5 , 0.5 ) + 1 ) / 2 ; let n = Math . floor ( Math . log ( ( Math . pow ( 5 , 0.5 ) ) * X ) / Math . log ( a ) ) ; let nth = nthFibo ( n ) ; let nplus = nthFibo ( n + 1 ) ; if ( Math . abs ( X - nth ) < Math . abs ( X - nplus ) ) return nth ; else return nplus ; } function getCost ( arr , n ) { let cost = 0 ; for ( let i = 0 ; i < n ; i ++ ) { let fibo = nearFibo ( arr [ i ] ) ; cost += Math . abs ( arr [ i ] - fibo ) ; } return cost ; } let arr = [ 56 , 34 , 23 , 98 , 7 ] ; let n = arr . length ; document . write ( getCost ( arr , n ) ) ;