# Question C: [Example 3] The sum of the first n terms of Fibonacci

Question C: [Example 3] The sum of the first n terms of Fibonacci

Time limit: 1 Sec Memory limit: 128 MB
Submission: 12. Solution: 8
[Submission][state][Discussion Edition [proposition people: quanxing] [TestData]

Title Description

We all know the Fibonacci sequence, f[1]=1,f[2]=1,f[3]=2,f[4]=3... that is, f[n]=f[n-1]+f[n-2]. Now, the problem is very simple. Input N and m, find the first n terms and take the modulus M.

input

Input n and m

1<=n<=2 000 000 000

1<=m<=1 000 000 010

output

Output the first n terms and modulus m.

sample input

`5 1000`

sample output

`12`

Ideas: Matrix fast power, plus derivation of the matrix recurrence formula of Fibonacci sequence, in addition, we know that the first n terms of the Fibonacci sequence and equal to the value of the n-2 terms of the Fibonacci sequence-1.

That is, S(n)=F(n+2)-1

Code:

```#include<bits/stdc++.h>

using namespace std;

#define ll long long

struct MUL

{

ll m[3][3];

}ans, res;

MUL mul(MUL a, MUL b, int n, int mod)//Matrix multiplication, defining the structure function, passing in the structure, returning the structure, is more convenient.

{

MUL tmp;

for (int i = 1; i <= n; i++)

{

for (int j = 1; j <= n; j++)

{

tmp.m[i][j] = 0;

}

}

for (int i = 1; i <= n; i++)

{

for (int j = 1; j <= n; j++)

{

for (int k = 1; k <= n; k++)

{

tmp.m[i][j] += ((a.m[i][k] % mod) *(b.m[k][j] % mod)) % mod;

}

}

}

return tmp;

}

ll quickpower(int N, int n, int mod)//Fast Power of Matrix

{

MUL C, res;//C is a constant matrix

memset(res.m, 0, sizeof(res.m));

C.m[1][1] = 1;

C.m[1][2] = 1;

C.m[2][1] = 1;

C.m[2][2] = 0;

for (int i = 1; i <= n; i++)res.m[i][i] = 1;//Unit matrix

while (N)

{

if (N & 1)

res = mul(res, C, n, mod);

C = mul(C, C, n, mod);

N = N >> 1;

}

return res.m[1][1];

}

int main()

{

ll n, mod;

cin >> n >> mod;

cout << quickpower(n + 1, 2, mod) % mod - 1 << endl;//S(n)=F(n+2)-1

}```

Tags: PHP

Posted on Fri, 11 Oct 2019 12:52:15 -0700 by 156418