Nth Fibonacci Number
Posted: 19 Apr, 2017
Difficulty: Easy
Nth term of Fibonacci series F(n), where F(n) is a function, is calculated using the following formula -
F(n) = F(n-1) + F(n-2),
Where, F(1) = F(2) = 1
Provided N you have to find out the Nth Fibonacci Number.
Input Format :
The first line of each test case contains a real number ‘N’.
Output Format :
For each test case, return its equivalent Fibonacci number.
Constraints:
1 <= N <= 10000
Where ‘N’ represents the number for which we have to find its equivalent Fibonacci number.
Time Limit: 1 second
Approach 1
Approach 2
Ans of ‘i-th’ number is = ‘ans[i-11+ans[i-2]’, so
- With the help of dynamic programming, we try to store the previous value as the previous value leads to a solution.
- So we use an array named as ‘dp’ of size ‘N+1’ to store the value.
- On the first index of ‘dp[0]=0’ we store ‘0’ and on the first index of ‘dp[1]=1’ we store ‘1’.
- Now run a loop and iterate through the “Nth”number like ‘dp[i]=dp[i-2]+dp[i-1]’.
- dp[n] will contain the Fibonacci number of “Nth”number.
- Return ‘dp[n]’.
Approach 3
- We take three integers a, b, c and we initialized a=0, b=1 as now we want to optimize the space by only storing “2” last numbers as we need only them.
- Now we run a loop up to our “Nth” number and by using property the next number is the sum of two previous numbers like “c=a+b.
- Now we update “a=b” and “b=c” at every step of the iteration.
- In this way when our loop finished “b” contains the “Nth” Fibonacci number.
- Return ‘b'.
SIMILAR PROBLEMS
Largest Element in the Array
Posted: 17 May, 2022
Difficulty: Easy
Count vowels, consonants, and spaces
Posted: 18 May, 2022
Difficulty: Easy
Check whether K-th bit is set or not
Posted: 20 May, 2022
Difficulty: Easy
Matrix Boundary Traversal
Posted: 20 May, 2022
Difficulty: Easy
Minimum Difference in an Array
Posted: 20 May, 2022
Difficulty: Easy