Given a number k, find the required minimum number of Fibonacci terms whose sum equal to k. We can choose a Fibonacci number multiple times.
Input : k = 4 Output : 2 Fibonacci term added twice that is 2 + 2 = 4. Other combinations are 1 + 1 + 2. 1 + 1 + 1 + 1 Among all cases first case has the minimum number of terms = 2. Input : k = 17 Output : 3
We can get any sum using Fibonacci numbers as 1 is a Fibonacci number. For example to get n, we can n times add 1. Here we need to to minimize the count of Fibonacci numbers that contribute to sum. So this problem is basically coin change problem with coins having fibonacci values. By taking some examples, we can notice that With Fibonacci coin values Greedy approach works.
Firstly we calculate Fibonacci terms till less than or equal to k. then start from the last term and keep subtracting that term from k until k >(nth term). Also along with this keep increasing the count of the number of terms.
When k < (nth Fibonacci term) move to next Fibonacci term which is less than or Equal to k. at last, print the value of count.
The stepwise algorithm is:
1. Find all Fibonacci Terms less than or equal to K. 2. Initialize count = 0. 3. j = Index of last calculated Fibonacci Term. 4. while K > 0 do: // Greedy step count += K / (fibo[j]) // Note that division // is repeated subtraction. K = K % (fibo[j]) j--; 5. Print count.
Below is the C++/java implementation of the above approach.
# Python3 code to find minimum number
# of fibonacci terms that sum to K.
# Function to calculate Fibonacci Terms
def calcFiboTerms(fiboTerms, K):
i = 3
# Calculate all Fibonacci terms
# which are less than or equal to K.
nextTerm = (fiboTerms[i – 1] +
fiboTerms[i – 2])
# If next term is greater than K
# do not push it in vector and return.
if nextTerm > K:
i += 1
# Function to find the minimum number of
# Fibonacci terms having sum equal to K.
# Vector to store Fibonacci terms.
fiboTerms = 
count, j = 0, len(fiboTerms) – 1
# Subtract Fibonacci terms from
# sum K until sum > 0.
while K > 0:
# Divide sum K by j-th Fibonacci
# term to find how many terms it
# contribute in sum.
count += K // fiboTerms[j]
K %= fiboTerms[j]
j -= 1
# Driver code
if __name__ == “__main__”:
K = 17
# This code is contributed
# by Rituraj Jain