xxxxxxxxxx
# Function for nth Fibonacci number
def Fibonacci(n):
# Check if input is 0 then it will
# print incorrect input
if n < 0:
print("Incorrect input")
# Check if n is 0
# then it will return 0
elif n == 0:
return 0
# Check if n is 1,2
# it will return 1
elif n == 1 or n == 2:
return 1
else:
return Fibonacci(n-1) + Fibonacci(n-2)
# Driver Program
print(Fibonacci(9))
# This code is contributed by Saket Modi
# then corrected and improved by Himanshu Kanojiya
xxxxxxxxxx
def Fab(num):
x=0
y=1
while(1):
print(x)
fab=x+y
x=y
y=fab
if x>=num:
break
Fab(100)
xxxxxxxxxx
n = int(input("No. of terms in febonacci sequence: "))
'''
Theory:
Here every number is the sum of the last two numbers
The sequence startes with 2 numbers that are 0,1
Sequence looks like: 0,1,1,2,3,5,8
'''
a,b=0,1
for i in range(n):
print(a,end=" ")
a,b=a+b,a
# END CODE
xxxxxxxxxx
i = int(input("Enter the first element :")) #First element in fibonacci series
j = int(input("Enter the second element :"))#second element in fibonacci series
k=0
z = [i,j]
for k in range(10):
t = i+j #For getting third element in series
z.append(t) #Adding elements to list
i=j #Swapping Positions
j=t
f = "".join([str(element) for element in z]) #conversion of list to string
l = int(f) #conversion of string to integer
print(z) #printing the series.
xxxxxxxxxx
user_input = int(input())
f = 0
s = 1
if user_input == 0:
print("The fibonacci series is", f)
else:
print(f, s, end=" ")
for i in range(2, user_input):
fib = f + s
print(fib, end=" ")
f = s
s = fib
xxxxxxxxxx
def iterativeFibonacci(n):
fibList[0,1]
for i in range(1, n+1):
fibList.append(fibList[i] + fibList[i-1])
return fibList[1:]
########################### Output ##################################
""" E.g. if n = 10, the output is --> [1,1,2,3,5,8,13,21,34,55] """
xxxxxxxxxx
#Using Recursion
def fib(n, lst = [0]):
"""Returns a list for n fib numbers | Time Complexity O(n)"""
l = []
if n == 1:
lst.append(1)
if n > 1:
l = fib(n-1, lst)
lst.append(l[-1]+l[-2])
return lst
#list of fibonacci numbers
lst = fib(int(input("val: ")))
print(lst)
xxxxxxxxxx
Input:
def Fib(n):
if n <= 1:
return n
else:
return (Fib(n - 1) + Fib(n - 2)) # function calling itself(recursion)
n = int(input("Enter the Value of n: ")) # take input from the user
print("Fibonacci series :")
for i in range(n):
print(Fib(i),end = " ")
Output:
Enter the value of n: 8
0 1 1 2 3 5 8 13