Program to find minimum number of Fibonacci numbers to add up to n in Python?

PythonServer Side ProgrammingProgramming

Suppose we have a number n; we have to find the minimum number of Fibonacci numbers required to add up to n.

So, if the input is like n = 20, then the output will be 3, as We can use the Fibonacci numbers [2, 5, 13] to sum to 20.

To solve this, we will follow these steps

  • res := 0

  • fibo := a list with values [1, 1]

  • while last element of fibo <= n, do

    • x := sum of last two elements of fibo

    • insert x into fibo

    • while n is non-zero, do

      • while last element of fibo > n, do

        • delete last element from fibo

      • n := n - last element of fibo

      • res := res + 1

  • return res

Let us see the following implementation to get better understanding

Example

class Solution:
   def solve(self, n):
      res = 0
      fibo = [1, 1]
      while fibo[-1] <= n:
         fibo.append(fibo[-1] + fibo[-2])

      while n:
         while fibo[-1] > n:
            fibo.pop()
         n -= fibo[-1]
         res += 1
      return res

ob = Solution()
n = 20
print(ob.solve(n))

Input

20

Output

3
raja
Published on 10-Nov-2020 09:28:33
Advertisements