#include<iostream>usingnamespacestd;intFibonacci(intn){if(n==0||n==1){returnn;}else{returnFibonacci(n-1)+Fibonacci(n-2);}}intmain(){intn;cout<<"Enter a positive integer: ";cin>>n;cout<<"The "<<n<<"th Fibonacci number is "<<Fibonacci(n)<<endl;return0;}
#include<iostream>usingnamespacestd;intFibonacci(intn){if(n==0||n==1){returnn;}intprev=0;intcurrent=1;intresult;for(inti=2;i<=n;i++){result=prev+current;prev=current;current=result;}returnresult;}intmain(){intn;cout<<"Enter a positive integer: ";cin>>n;cout<<"The "<<n<<"th Fibonacci number is "<<Fibonacci(n)<<endl;return0;}
#include<iostream>#include<vector>usingnamespacestd;longlongFibonacci(intn){vector<longlong>dp(n+1,0);dp[0]=0;dp[1]=1;for(inti=2;i<=n;i++){dp[i]=dp[i-1]+dp[i-2];}returndp[n];}intmain(){intn;cout<<"Enter a positive integer: ";cin>>n;cout<<"The "<<n<<"th Fibonacci number is "<<Fibonacci(n)<<endl;return0;}
#include<iostream>#include<vector>usingnamespacestd;longlongFibonacci(intn,vector<longlong>&memo){if(memo[n]!=-1){returnmemo[n];}if(n==0){memo[n]=0;}elseif(n==1){memo[n]=1;}else{memo[n]=Fibonacci(n-1,memo)+Fibonacci(n-2,memo);}returnmemo[n];}intmain(){intn;cout<<"Enter a positive integer: ";cin>>n;vector<longlong>memo(n+1,-1);cout<<"The "<<n<<"th Fibonacci number is "<<Fibonacci(n,memo)<<endl;return0;}
#include<iostream>#include<vector>usingnamespacestd;typedefvector<vector<longlong>>matrix;matrixmultiply(matrixa,matrixb){intn=a.size();intm=b[0].size();intl=a[0].size();matrixc(n,vector<longlong>(m,0));for(inti=0;i<n;i++){for(intj=0;j<m;j++){for(intk=0;k<l;k++){c[i][j]+=a[i][k]*b[k][j];}}}returnc;}matrixpower(matrixa,intn){if(n==1){returna;}matrixhalf=power(a,n/2);matrixresult=multiply(half,half);if(n%2==1){result=multiply(result,a);}returnresult;}longlongFibonacci(intn){if(n==0){return0;}matrixbase={{1,1},{1,0}};matrixresult=power(base,n-1);returnresult[0][0];}intmain(){intn;cout<<"Enter a positive integer: ";cin>>n;cout<<"The "<<n<<"th Fibonacci number is "<<Fibonacci(n)<<endl;return0;}
#include<iostream>#include<cmath>usingnamespacestd;longlongFibonacci(intn){doublephi=(1+sqrt(5))/2;doublepsi=(1-sqrt(5))/2;returnround((pow(phi,n)-pow(psi,n))/sqrt(5));}intmain(){intn;cout<<"Enter a positive integer: ";cin>>n;cout<<"The "<<n<<"th Fibonacci number is "<<Fibonacci(n)<<endl;return0;}