方法一 用数组开,一般开到1e7,1e8 左右的数组就是极限了 对时间也是挑战
#include<bits/stdc++.h> using namespace std; const int maxn=1e8+10; int a[maxn]; int32_t main() { a[1]=1; a[2]=1; for(int i=3;i<maxn;i++) a[i]=a[i-1]%10000000+a[i-2]%100000000; cout<<a[maxn-1]<<endl; }
方法二 求第多少个斐波那契数 时间还是个问题
#include<bits/stdc++.h> using namespace std; const int maxn=1e8+10; int32_t main() { int x; x=1000; if(x==1) cout<<1<<endl; if(x==2) cout<<1<<endl; if(x>3) { int a=1; int b=1; int c=0; for(int i=3;i<=x;i++) { c=(a+b)%100000000; a=b%100000000; b=c; } cout<<c<<endl; } }
方法三
通项公式 a[n]=1/sqrt(5) ( ((1+sqrt(5))/2 )^n-((1-sqrt(5))/2)^n );
这不是重点 重要的是 矩阵 求斐波那契数列
不是很会矩阵 推荐这个博客 https://blog.csdn.net/flyfish1986/article/details/48014523
也可以看我的代码(看了过程再来看比较好)
#include<bits/stdc++.h> using namespace std;
#define int long long const int k=1e8; int fj(int n) { if(n==1) return 1; int m=n-2; int a11=1,a12=1,a21=1,a22=0; int t1=1,t2=0; int b11=1,b12=1,b21=1,b22=0;// kau su mi de while(m) { if(m%2==1) { int c11=a11*b11+a12*b21; int c12=a11*b12+a12*b22; int c21=a21*b11+a22*b21; int c22=a21*b12+a22*b22; a11=c11%k; a12=c12%k; a21=c21%k; a22=c22%k; m--; } else if(m%2==0) { int c11=b11*b11+b12*b21; int c12=b11*b12+b12*b22; int c21=b21*b11+b22*b21; int c22=b21*b12+b22*b22; b11=c11%k; b12=c12%k; b21=c21%k; b22=c22%k; m=m/2; } } return a11; } int32_t main() { int n; cin>>n; int c=fj(n); cout<<c<<endl; }
{ f[n+1] f[n] } ={ 1 1} ^n
{ f[n] f[n-1} = {1 0}
#include<iostream> #include<cstdio> using namespace std; const int maxn=1e5+10; const int mod=10000; int MOD=mod; struct Matrix { int a[2][2]; void init() { for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) a[i][j] = 0; } } void _init() { init(); for (int i = 0; i < 2; i++) a[i][i] = 1; } }A, B; Matrix mul(Matrix a, Matrix b) { Matrix ans; ans.init(); for (int i = 0; i <2; i++) { for (int j = 0; j < 2; j++) { if(a.a[i][j]) { for (int k = 0; k <2; k++) ans.a[i][k] = (ans.a[i][k] + 1LL * a.a[i][j] * b.a[j][k]) % MOD; } } } return ans; } Matrix q_pow(Matrix a, int k) { Matrix ans; ans._init(); if(k <= 0) return ans; while(k) { if(k&1) ans = mul(ans, a); a = mul(a, a); k >>= 1; } return ans; } int main(){ int n,m; while(1){ scanf("%d",&n); if(n==-1) break; Matrix a; a.init(); a.a[0][0]=1; a.a[0][1]=1; a.a[1][0]=1; a=q_pow(a,n); printf("%d ",a.a[0][1]); } }