Minimum Fibonacci terms with sum equal to K in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a number K. Our task is to find the Minimum Fibonacci terms with sum equal to K.

Fibonacci Series generates subsequent numbers by adding two previous numbers. The Fibonacci series starts from two numbers − F0 & F1. The initial values of F0 & F1 can be taken 0, 1 or 1, 1 respectively.

Fibonacci Series is 0 1 1 2 3 5 8 13

Let’s take an example to understand the problem,


K = 5




The sum 5 can be made using 3 and 2.

Solution Approach

By using Fibonacci numbers we can get the sum as any number as 1 is a Fibonacci number. Adding 1 n times can give the sum as n. Our task is to minimize the count of Fibonacci numbers that gives the sum. We can achieve the solution by taking the base from the coin change problem where the coins are having fibonacci number values. In programming language, the technique to solve this problem is called the greedy approach.

At first, we sum the Fibonacci numbers till less than or equal to a sum n. Then starting from the last term we subtract that term from n until n>kth term. And side by side, increase the count of the number of terms. At point when n<kth term, move to the adjacent Fibonacci term which is less than or equal to n and print the value of that count.


  • Create a function to calculate the Fibonacci terms.

  • Calculate all the Fibonacci terms which are less than or equal to n.

  • If the next term is greater than n, do not push it in vector and return.

  • Create a function to find the minimum number of Fibonacci terms having sum equal to n.

  • Initialise a vector to store Fibonacci terms.

  • Subtract Fibonacci terms from sum n until the sum>0.

  • Divide the sum n by jth Fibonacci term to find the number of terms which contribute to the sum.

  • Print the obtained count as output.


Program to illustrate the working of our solution

#include <bits/stdc++.h>
using namespace std;
void findFiboTerms(vector<int>& fiboVals, int K){
   int i = 3, nextTerm;
   while (1) {
      nextTerm = fiboVals[i - 1] + fiboVals[i - 2];
      if (nextTerm > K)
int findTermForSum(int K){
   vector<int> fiboVals;
   findFiboTerms(fiboVals, K);
   int termCount = 0, j = fiboVals.size() - 1;
   while (K > 0) {
      termCount += (K / fiboVals[j]);
      K %= (fiboVals[j]);
   return termCount;
int main(){
   int K = 11;
   cout<<"Minimum Fibonacci terms with sum equal to K is "<<findTermForSum(K);
   return 0;


Minimum Fibonacci terms with sum equal to K is 2
Updated on 14-Feb-2022 09:13:05