The Fibonacci numbers are the numbers in the following integer sequence.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ……..
In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation
Fn = Fn-1 + Fn-2
with seed values
F0 = 0 and F1 = 1.
Method 1 ( Use recursion ) :
Python
# Function for nth Fibonacci numberdef Fibonacci(n): if n<=0: print("Incorrect input") # First Fibonacci number is 0 elif n==1: return 0 # Second Fibonacci number is 1 elif n==2: return 1 else: return Fibonacci(n-1)+Fibonacci(n-2)# Driver Programprint(Fibonacci(9))#This code is contributed by Saket Modi |
chevron_right
filter_none
Output:
21
Method 2 ( Use Dynamic Programming ) :
Python
# Function for nth fibonacci number - Dynamic Programing# Taking 1st two fibonacci nubers as 0 and 1FibArray = [0,1]def fibonacci(n): if n<=0: print("Incorrect input") elif n<=len(FibArray): return FibArray[n-1] else: temp_fib = fibonacci(n-1)+fibonacci(n-2) FibArray.append(temp_fib) return temp_fib# Driver Programprint(fibonacci(9))#This code is contributed by Saket Modi |
chevron_right
filter_none
Output:
21
Method 3 ( Space Optimized):
Python
# Function for nth fibonacci number - Space Optimisataion# Taking 1st two fibonacci numbers as 0 and 1def fibonacci(n): a = 0 b = 1 if n <= 0: print("Incorrect input") elif n == 1: return b else: for i in range(2,n): c = a + b a = b b = c return b# Driver Programprint(fibonacci(9))#This code is contributed by Saket Modi |
chevron_right
filter_none
Output:
21
Please refer complete article on Program for Fibonacci numbers for more details!
Recommended Posts:
- Python Program for n\'th multiple of a number in Fibonacci Series
- Python Program for Zeckendorf\'s Theorem (Non-Neighbouring Fibonacci Representation)
- Python Program for How to check if a given number is Fibonacci number?
- Python Program for n-th Fibonacci number
- Python | Plotting Fibonacci spiral fractal using Turtle
- Python | Find fibonacci series upto n using lambda
- Python program to check if the list contains three consecutive common numbers in Python
- Python Program for GCD of more than two (or array) numbers
- Python Program for Common Divisors of Two Numbers
- Python Program for cube sum of first n natural numbers
- Python Program for Sum of squares of first n natural numbers
- Python program to find all Strong Numbers in given list
- Python program to print all negative numbers in a range
- Python program to add two numbers
- Python program to print all Prime numbers in an Interval
- Python program to count Even and Odd numbers in a List
- Python program to print all even numbers in a range
- Python program to print all odd numbers in a range
- Python program to print odd numbers in a List
- Python program to print even numbers in a list
Improved By : grohith70

