# Find the Minimum Number of Fibonacci Numbers Whose Sum Is K in C++

C++Server Side ProgrammingProgramming

Suppose we have a number k, we have to find the minimum number of Fibonacci numbers whose sum is equal to the k, whether a Fibonacci number could be used multiple times.

So, if the input is like k = 7, then the output will be 2, as the Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ... For k = 7 we can use 2 + 5 = 7.

To solve this, we will follow these steps −

• Define an array f

• insert 0 at the end of f

• insert 1 at the end of f

• while last element of f <= k, do −

• insert (last element of f + second last element of f) into f

• ret := 0

• j := last index of f

• while (j >= 0 and k > 0), do −

• if f[j] <= k, then −

• k := k - f[j]

• (increase ret by 1)

• Otherwise

• (decrease j by 1)

• return ret

## Example

Let us see the following implementation to get a better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int findMinFibonacciNumbers(int k) {
vector<int> f;
f.push_back(0);
f.push_back(1);
while (f.back() <= k) {
f.push_back(f[f.size() - 1] + f[f.size() - 2]);
}
int ret = 0;
int j = f.size() - 1;
while (j >= 0 && k > 0) {
if (f[j] <= k) {
k -= f[j];
ret++;
}
else
j--;
}
return ret;
}
};
main(){
Solution ob;
cout << (ob.findMinFibonacciNumbers(7));
}

## Input

7

## Output

2
Published on 17-Nov-2020 11:54:15