Fibonacci sum n terms

Fibonacci sum n terms

# 题 意

Find the sum of the first n terms of Fibonacci

1 ≤ n ≤ 210

# Explanations 

Large data range can only accept O (√n) or O (log n)

Matrix recursion speeds up, F (n) three-dimensional vector representation {f (n), f (n + 1), s (n)}

Multiplication matrix

      0   1    0

A=  1    1    1

      0   0    1

That is, F (0) · A n

Fast power can reach O (3 3 logn)

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

 

Guess you like

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