Question:
Fibonacci series, F [0] = 0, F [1] = 1, F [N] = f [N-2] + F [n-1], n> 1
Given N (0 <= n <2 ^ 32) and M, evaluate f [N] mod m.
Solution:
N is too large, so we cannot use the cyclic recursive Calculation of O (n ).
Conclusion: For matrices | 1 1 |, and matrices | Fn Fn-1 |, after the two are multiplied to obtain a new matrix | Fn + 1FN|, FN indicates the nth Number of fiber ACCI
| 1 0 | | Fn-1 Fn-2 | | Fn Fn-1
Therefore, we can use the rapid power modulo + matrix multiplication of O (logn) to calculate f [N].
Fast Power Process: A ^ B =
1, B = 0
A, B = 1
A ^ (B/2) * A ^ (B/2), B is even
A * a ^ (b-1), B is odd
#include<iostream>#include<cstdio>using namespace std;struct Node{ int arr[2][2];}o;Node MUL(Node a, Node b,const int &m){ Node tmp; tmp.arr[0][0] = (a.arr[0][0]*b.arr[0][0] + a.arr[0][1]*b.arr[1][0]) % m; tmp.arr[0][1] = (a.arr[0][0]*b.arr[0][1] + a.arr[0][1]*b.arr[1][1]) % m; tmp.arr[1][0] = (a.arr[1][0]*b.arr[0][0] + a.arr[1][1]*b.arr[1][0]) % m; tmp.arr[1][1] = (a.arr[1][0]*b.arr[0][1] + a.arr[1][1]*b.arr[1][1]) % m; return tmp;}Node exp(Node mat, int n, const int &m){ if(n == 1) return o; if(n & 1) { return MUL(o, exp(mat,n-1,m), m); } else { Node tmp = exp(mat,n>>1, m); return MUL(tmp,tmp,m); }}int main(){ o.arr[0][0] = o.arr[0][1] = o.arr[1][0] = 1; o.arr[1][1] = 0; int cas; scanf("%d",&cas); while(cas --) { int n,m; scanf("%d%d",&n,&m); if(n == 0) { printf("0\n"); continue; } Node f = o; f = exp(f,n,m); printf("%d\n",f.arr[0][1] % m); }}