Program to find Nth Fibonacci Number in Python


Suppose we have a number n, we have to find the nth Fibonacci term. As we know the ith Fibonacci term f(i) = f(i-1) + f(i-2), the first two terms are 0, 1.

So, if the input is like 15, then the output will be 610

To solve this, we will follow these steps −

  • first := 0, second := 1
  • for i in range 2 to n, do
    • temp := first + second
    • first := second
    • second := temp
  • return second

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, n):
      first = 0
      second = 1
      for _ in range(2, n+1):
         temp = first + second
         first = second
         second = temp
      return second
ob = Solution()
print(ob.solve(15))

Input

15

Output

610

Updated on: 06-Oct-2020

480 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements