Minimum Fibonacci terms with sum equal to K | Java code to find the minimum number of Fibonacci terms that sum to k . ; Function to calaculate Fibonacci Terms ; Calculate all Fibonacci terms which are less than or equal to k . ; If next term is greater than k do not add in arraylist and return . ; Function to find the minimum number of Fibonacci terms having sum equal to k . ; ArrayList to store Fibonacci terms . ; Subtract Fibonacci terms from sum k until sum > 0. ; Divide sum k by j - th Fibonacci term to find how many terms it contribute in sum . ; driver code
import java . util . * ; class GFG { public static void calcFiboTerms ( ArrayList < Integer > fiboterms , int k ) { int i = 3 , nextTerm = 0 ; fiboterms . add ( 0 ) ; fiboterms . add ( 1 ) ; fiboterms . add ( 1 ) ; while ( true ) { nextTerm = fiboterms . get ( i - 1 ) + fiboterms . get ( i - 2 ) ; if ( nextTerm > k ) return ; fiboterms . add ( nextTerm ) ; i ++ ; } } public static int fibMinTerms ( int k ) { ArrayList < Integer > fiboterms = new ArrayList < Integer > ( ) ; calcFiboTerms ( fiboterms , k ) ; int count = 0 , j = fiboterms . size ( ) - 1 ; while ( k > 0 ) { count += ( k / fiboterms . get ( j ) ) ; k %= ( fiboterms . get ( j ) ) ; j -- ; } return count ; } public static void main ( String [ ] args ) { int k = 17 ; System . out . println ( fibMinTerms ( k ) ) ; } }