Nth Fibonacci Number
Nth Fibonacci Number
Send Feedback
Nth Fibonacci Number
F(n) = F(n-1) + F(n-2),
Where, F(1) = 1,
F(2) = 1
The first line of each test case contains a real number ‘N’.
For each test case, return its equivalent Fibonacci number.
1 <= N <= 10000
Where ‘N’ represents the number for which we have to find its equivalent Fibonacci number.
Time Limit: 1 second
6
8
Now the number is ‘6’ so we have to find the “6th” Fibonacci number
So by using the property of the Fibonacci series i.e
[ 1, 1, 2, 3, 5, 8, 13, 21]
So the “6th” element is “8” hence we get the output.
#include<iostream>using namespace std;
int main(){ //Write your code here. int n1,n2; n1=n2=1; int n; cin>>n; int fab=0; if(n==1 || n==2) cout<<1<<endl; else { for(int i=2;n>i;i++){ fab=n1+n2; n1=n2; n2=fab; } cout<<fab<<endl; } }
Comments
Post a Comment