Minimize cost of converting all array elements to Fibonacci Numbers | Java program for the above approach ; 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
import java . util . * ; import java . lang . * ; class GFG { static int nthFibo ( int n ) { double a = ( Math . pow ( 5 , 0.5 ) + 1 ) / 2 ; double b = ( - 1 * ( Math . pow ( 5 , 0.5 ) ) + 1 ) / 2 ; double r = Math . pow ( 5 , 0.5 ) ; double ans = ( Math . pow ( a , n ) - Math . pow ( b , n ) ) / r ; return ( int ) ans ; } static int nearFibo ( int X ) { double a = ( Math . pow ( 5 , 0.5 ) + 1 ) / 2 ; int n = ( int ) ( Math . log ( ( Math . pow ( 5 , 0.5 ) ) * X ) / Math . log ( a ) ) ; int nth = nthFibo ( n ) ; int nplus = nthFibo ( n + 1 ) ; if ( Math . abs ( X - nth ) < Math . abs ( X - nplus ) ) return nth ; else return nplus ; } static int getCost ( int arr [ ] , int n ) { int cost = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int fibo = nearFibo ( arr [ i ] ) ; cost += Math . abs ( arr [ i ] - fibo ) ; } return cost ; } public static void main ( String [ ] args ) { int arr [ ] = { 56 , 34 , 23 , 98 , 7 } ; int n = arr . length ; System . out . print ( getCost ( arr , n ) ) ; } }