nth Fibonacci number in python
Hi, today we will learn how to find nth Fibonacci number in python. At first, we should know about what is the Fibonacci series.
Find nth Fibonacci number in Python
Fibonacci Series:
Basically Fibonacci series is a series which follows a special sequence to store numbers.
Rule: ( 2nd previous number + 1st previous number ) = 3rd number ( Current number ).
Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34…….
Explanation:
- 0 is the first number
Then series = 0 - 1 is the 2nd number
Then series = 0,1 ( after 1 the Fibonacci rule started ) - (0+1) = 1
Then series = 0,1,1 - (1+1) = 2
Then series = 0,1,1,2 - (1+2) = 3
Then series = 0,1,1,2,3 - (2+3) = 5
Then series = 0,1,1,2,3,5 - (3+5) = 8
Then series = 0,1,1,2,3,5,8 - (5+8) = 13
Then series = 0,1,1,2,3,5,8,13 - (8+13) = 21
Then series = 0,1,1,2,3,5,8,13,21 - (13+21) = 34
Then series = 0,1,1,2,3,5,8,13,21,34 and so on..
Here is the optimized and best way to print Fibonacci sequence: Fibonacci series in python (Time complexity:O(1))
Get the nth number in Fibonacci series in python
This article covered how to create a Fibonacci series in python. This python program is very easy to understand how to create a Fibonacci series. After the creation of a Fibonacci series, we can find the nth Fibonacci number in the series.
Code:
n = int(input('Enter : ')) fibo_nums = [0,1] i=1 if(n==1 or n==2): print(n,'th Prime Number is :',fibo_nums[n-1]) print('Fibonacci Series :', fibo_nums) elif(n>2): while (True): fib = fibo_nums[i-1]+fibo_nums[i] fibo_nums.append(fib) if(len(fibo_nums)==n): break else: i+=1 print(n,'th Fibonacci Number is :', fibo_nums[n-1]) print('Fibonacci Series is :', fibo_nums) else: print('Please Enter A Valid Number')
Output:
Leave a Reply