Python Program For Fibonacci Number Using Dynamic Programming

Vipin | Thu, 04 Jun, 2020 | 315

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

 

# Function for nth fibonacci number - Dynamic Programing 
# Taking 1st two fibonacci nubers as 0 and 1 

FibArray = [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 

# call to function 

print(fibonacci(10)) 

Output : 

34

0 comments
Leave a comment