Description
Fibonacci sequence is a set of numbers that start with 1 or 0 followed by a 1 proceeds on the rule that each number.
Fibonacci number is equal to the sum of the preceding two numbers.
F(n) = 0, 1, 1, 2, 3, 5, 8, 13....
In mathematical terms, the sequence F(n) of Fibonacci number is defined by the recurrence relation.
F(n) = F(n-1) + F(n-2)
Where seed values are :
F(0) = 0 and F(1) = 1
Method: 1 - Using For Loop
For printing the sequence of Fibonacci sequence with the help of for loop.
- Take the input of values, want to generate the Fibonacci sequence.
- Initilized a = 0 and b = 0
- if n < = 0 , then print the Message for used "Please Enter the Positive Integer Number" otherwise go to step 4
- if n == 1, it will print the 1 terms of the Fibonacci Series. otherwise go to step 5
- Print the two Starting two terms of the fiboanacci Series and after that Start a for loop while range is n -2 then print the sequence of the Fibonacci Series.
- print(c, end =" "), here c = a + b
- update the values , a = b, b = c and so, up to the required term.
n = int(input("How many Terms the users wants to print : "))
a = 0
b = 1
if n<=0:
print("Please Enter the Positive Integer Number")
else:
if n == 1:
print("Fibonacci Sequence of the Number up to ", n)
print(a, end=" ")
else:
print("Sequence ( Series ) of Fibonacci : ")
print(a , b, end = " ")
for i in range(n-2):
c = a + b
print(c, end = " ")
a = b
b = c
Method:2 - Using While loop
- Take input the number of values to generate the Fibonacci Series.
- Initialize the count = 0, a = 0, and b = 1
- if the n < = 0
- print"Error Message" as it is not a valid number for Gibonacci Series.
- if n = 1, it will print a value
- while count < n
- print(a)
- c = a + b
- update the variable a = b, b = c and so no, upto the required term.
n = int(input("How many Terms the users wants to print : "))
count = 0
a = 0
b = 1
if n<=0:
print("Please Enter the Positive Integer Number")
elif n == 1:
print("Fibonacci Sequence of the Number up to ", n)
print(a, end=" ")
else:
print("Sequence ( Series ) of Fibonacci : ")
while count < n:
print(a, end = " ")
c = a + b
a = b
b = c
count += 1
Method: 3 - Using Recursion
def Fibonacci(n):
if n < 0:
print("Enter the Positive Integer Number")
elif n == 0:
return 0
elif n == 1 :
return 0
elif n == 2 or n == 3:
return 1
else:
return Fibonacci(n-1) + Fibonacci(n-2)
n = int(input("How many Terms the users wants to print : "))
print(Fibonacci(n))
Thanks...
Please Given Your Suggesstion in Comment Box.
Recommended Posts
Find maximum of two number in python programming language
Maximum of two number in Python - Using max() function , Using if else statement, Using Ternary operator and Using Lambda function.