Table of Contents
Algorithm: Formula and Logic
As a result, the following formula is used to calculate the series:
xn = xn-1 + xn-2; xn is the nth term number
The prior term was xn-1 (n-1)th term
The phrase before that was xn-2 (n-2)th term.
The number after that is the sum of the two numbers before it.
(1+0) = 1 is the 3rd element.
(1+1) = 2 is the 4th element.
(2+1) = 3 is the 5th element.
Implementation in Python or Code Logic
In iterative approach, each iteration of the loop in the preceding method prints the first value. Each iteration calculates the next value by adding the two previous values together, then updates the first and second values till the nth count. In below example, we will find Fibonacci sequence of 6th term.
Iterative Approach: Example Code
def fib_iter(n): a=1 b=1 if n==1: print('0') elif n==2: print('0','1') else: print("Iterative Approach: ", end=' ') print('0',a,b,end=' ') for i in range(n-3): total = a + b b=a a= total print(total,end=' ') print() return b fib_iter(6)
Recursion occurs in Python programming when a function calls itself directly or indirectly. A recursive function is a name given to the related function. Specific issues can be solved quickly using a recursive approach. In below example, we will find the term sequence of 7th term.
Recursive Approach: Example Code
def recur_fibo(n): if n <= 1: return n else: return(recur_fibo(n-1) + recur_fibo(n-2)) nterms = 7 if nterms <= 0: print("Plese enter a positive integer") else: print("Recursive Approach:") for i in range(nterms): print(recur_fibo(i))
nth term Python Program using dynamic programming and space optimization
The Fibonacci number sequence Fn is described mathematically by the recurrence relation.
Fn is equal to the sum of Fn-1 and Fn-2.
In terms of seed or initial values: F0 equals 0 and F1 equals 1.
In below example, we will take 9 as n-th term or nth count.
Note: We can only give a positive integer to find Fibonacci sequence.
def fibonacci(n): a = 0 b = 1 if n < 0: print("Incorrect input") elif n == 0: return a elif n == 1: return b else: for i in range(2, n): c = a + b a = b b = c return b print("nth Term:",fibonacci(9))
In conclusion, we discussed the Fibonacci series that is a mathematical term. We discussed various things like its definition, algorithm, logic, flowchart, and so on. In Python, we performed Fibonacci series programs using different approaches. In terms of programming language, to make things more understandable.