

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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
- Related Questions & Answers
- Program to find nth Fibonacci term in Python
- Program to find Nth Fibonacci Number in Python
- C++ program to find Nth Non Fibonacci Number
- C++ program to find nth term of the series 5, 2, 13 41,...
- Python Program for nth multiple of a number in Fibonacci Series
- Python Program to Find the Fibonacci Series Using Recursion
- Program to find Nth Even Fibonacci Number in C++
- Program to find nth term in Look and Say Sequence in Python
- C++ program to find Nth term of series 1, 4, 15, 72, 420…
- C++ program to find Nth term of the series 1, 5, 32, 288 …
- C++ program to find Nth term of the series 1, 8, 54, 384…
- C++ program to find Nth term of the series 3, 14, 39, 84…
- Python Program to Find the Fibonacci Series without Using Recursion
- JavaScript code to find nth term of a series - Arithmetic Progression (AP)
- C++ program to find Nth term of the series 1, 6, 18, 40, 75, ….
Advertisements