Minimum Fibonacci terms with sum equal to K | Function to calculate Fibonacci Terms ; Calculate all Fibonacci terms which are less than or equal to K . ; If next term is greater than K do not push it in vector and return . ; Function to find the minimum number of Fibonacci terms having sum equal to K . ; Vector 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
function calcFiboTerms ( fiboTerms , K ) { var i = 3 , nextTerm ; fiboTerms . push ( 0 ) ; fiboTerms . push ( 1 ) ; fiboTerms . push ( 1 ) ; while ( 1 ) { nextTerm = fiboTerms [ i - 1 ] + fiboTerms [ i - 2 ] ; if ( nextTerm > K ) return ; fiboTerms . push ( nextTerm ) ; i ++ ; } } function findMinTerms ( K ) { var fiboTerms = [ ] ; calcFiboTerms ( fiboTerms , K ) ; var count = 0 ; var j = fiboTerms . length - 1 ; while ( K > 0 ) { count += parseInt ( K / fiboTerms [ j ] ) ; K %= ( fiboTerms [ j ] ) ; j -- ; } return count ; } var K = 17 ; document . write ( findMinTerms ( K ) ) ;