![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find minimum number of Fibonacci numbers to add up to n in Python?
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
Advertisements