Skip to content

Instantly share code, notes, and snippets.

@haroldxin
Created September 19, 2014 13:42
Show Gist options
  • Save haroldxin/a8618c662e46c998535a to your computer and use it in GitHub Desktop.
Save haroldxin/a8618c662e46c998535a to your computer and use it in GitHub Desktop.
Fibonacci
#include <iostream>
#include <cstdio>
#include <vector>
using namespace std; //爲什麽總是忘!!!
typedef vector<int> vec;
typedef vector<vec> mat;
typedef long long lint;
const int M = 10000;
//caculate A*B
mat martix(mat &A,mat &B) {
mat C(A.size(),vec(B[0].size()));
for(int i=0;i<A.size();i++){
for (int k=0;k<B.size();k++){
for(int j=0;j<B[0].size();j++){
C[i][j]=(C[i][j]+A[i][k]*B[k][j])%M;
}
}
}
return C;
}
//Caculate A^n
mat power(mat A,lint n){
mat B(A.size(),vec(A.size()));
for (int i=0;i<A.size();i++){
B[i][i]=1;
}
while(n>0){//快速冪運算
if (n & 1)B = martix(B,A);
A=martix(A,A);
n >>= 1;
}
return B;
}
lint n;
void slove (){
mat A(2,vec(2));
A[0][0]=1;A[0][1]=1;
A[1][0]=1;A[1][1]=0;
A=power(A,n);
printf("%d\n",A[1][0]);
}
int main (){
cin >> n;
slove();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment