Fibonacci (Matrix multiplication acceleration

Fibonacci

# 题 意

Find the value of Fibonacci's nth modulus 10000 with multiple sets of inputs

# Explanations

f (n) = {f (n), f (n + 1)}, use such a row vector to represent the Fibonacci sequence,

Each time the matrix {{0,1}, {1,1}} becomes {f (n + 1), f (n) + f (n + 1)}, it can be recursive

Matrix multiplication can use fast power

The last is O (2 3 logn)

 1 #include<bits/stdc++.h>
 2 #define ll long long
 3 using namespace std;
 4 const int N=2e6,mod = 10000;
 5 int n;
 6 void mul(int f[2],int a[2][2]){
 7     int c[2];
 8     memset(c,0,sizeof c);
 9     for(int i=0;i<2;i++)
10         for(int k=0;k<2;k++)
11             c[i]=(c[i]+(ll)f[k]*a[k][i])%mod;
12     memcpy(f,c,sizeof c);
13 }
14 void mulself(int a[2][2]){
15     int c[2][2];
16     memset(c, 0, sizeof c);
17     for (int i = 0; i < 2; i++) {
18         for (int j = 0; j < 2; j++)
19             for (int k = 0; k < 2; k++)
20                 c[i][j] = (c[i][j] + (ll) a[i][k] * a[k][j]) % mod;
21     }
22     memcpy(a, c, sizeof c);
23 }
24 int main(){
25     while(cin>>n && n!=-1){
26         int a[2][2]={{0,1},{1,1}};
27         int f[2]={0,1};
28         while(n){
29             if(n&1) mul(f,a);
30             mulself(a);
31             n>>=1;
32         }
33         cout<<f[0]<<endl;
34     }
35 }

 

Guess you like

Origin www.cnblogs.com/hhyx/p/12704739.html