Python Program to calculate the n-th term of a Fibonacci Series

Here, we will figure out how to compute the n-th term of a Fibonacci arrangement utilizing python program?

Python program to ascertain n-th term of Fibonacci arrangement with the assistance to two methodologies (there are numerous ways to deal with compute n-th term).

Portrayal:

  1. First Approach: Dynamic Programming: In this methodology, we figure every one of the terms of Fibonacci arrangement up to n and on the off chance that we have to ascertain whatever another term which is littler than n, at that point we don’t need to compute it once more.
  2. Second Approach: By Formula In this methodology, we compute the n-th term of Fibonacci arrangement with the assistance of a recipe.
    Formula:
    phi = ( 1 + sqrt(5) ) / 2
    An = phin/ sqrt(5)

Example:

    Input:
    for n = 5
    for n = 8

    Output:
    a5  = 5
    a8 = 21

Strategy: Dynamic Programming Approach:

    L[0] = 0, L[1] = 1
    For loop from 2 to n+1
        L[i] = L[i-1] + L[i -2]
    End of for

As you may see that we are likewise putting away each determined worth, so we can likewise utilize them later if essential.

This is the advantage of Dynamic Programming over Recursion.

Python code to ascertain n-th term of a Fibonacci arrangement:

def dynamic_fibonacci(n):
    '''
    This function will calculate fobonacci
    series with the help of dynamic
    programming.
    '''
    l = [0]*(n+1)
    l[0] = 0
    l[1] = 1
    for i in range(2, n+1):
        l[i] = l[i-1] + l[i-2]

    return l

    # Time complexity O(n)


def fibonacci_by_formula(n):
    '''
    This function will calculate n-th
    term of fibonacci series with the
    help of a formula.
    '''
    from math import sqrt
    
    phi = (1 + sqrt(5))/2

    fib = round(pow(phi, n)/sqrt(5))

    return fib

    # Time complexity O(1)

def main():
    n = 8
    lst = dynamic_fibonacci(n)
    x = fibonacci_by_formula(n)

    print('By Dynamic Programming:',lst[n])
    print()
    print('By Formula:',x)

main()

Output:

By Dynamic Programming: 21

By Formula: 21

Leave a Comment

error: Alert: Content is protected!!