- 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 Fibonacci series results up to nth term in Python
Suppose we have a number n. We have to find the sum of first n Fibonacci terms (Fibonacci sequence up to n terms). If the answer is too large then return result modulo 10^8 + 7.
So, if the input is like n = 8, then the output will be 33 as first few Fibonacci terms are 0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 = 33
To solve this, we will follow these steps −
- m := 10^8+7
- memo := a new map
- Define a function solve() . This will take n, m
- if n is in memo, then
- return memo[n]
- memo[n] := n when n < 2 otherwise (solve(n-1, m) +solve(n-2, m)) mod m
- return memo[n]
- From the main method get the list of memo values and take their sum.
Example
Let us see the following implementation to get better understanding −
m = 10**8+7 memo = {} def solve(n, m): if n in memo: return memo[n] memo[n] = n if n < 2 else (solve(n-1, m)+solve(n-2, m)) % m return memo[n] n = 8 solve(n, m) print(sum(list(memo.values())[:n]))
Input
8
Output
33
Advertisements