Question: Calculate the N fib number and the 2 ^ m model.
Analysis: divide, fast power.
For more information, seeFibonacci SeriesHttp://blog.csdn.net/mobius_strip/article/details/8222309)
Medium4. Calculation of Fib 3: Divide and conquer;
Set JN to the number of rabbits with fertility in the nth month, and an to the number of rabbits in the first month. The following recursive matrix is obtained:
Where
This can be simply proved by mathematical induction, and we will not prove it here;
Then, we apply the preceding Rapid power algorithm to the matrix and obtain a logarithm-level fib algorithm.
Note: When n is 0.
# Include <iostream> # include <cstdlib> # include <cstdio> using namespace STD;/*, the result is in ANS */long mat [2] [2] = {0, 1, 1}; long ans [2] [2]; long long tem [2] [2]; // matrix multiplication void MUL (long a [] [2], long B [] [2], long long C [] [2], int mod) {for (INT I = 0; I <2; ++ I) for (Int J = 0; j <2; ++ J) A [I] [J] = 0ll; For (INT I = 0; I <2; ++ I) for (Int J = 0; j <2; ++ J) for (int K = 0; k <2; ++ K) A [I] [J] = (a [I] [J] + B [I] [k] * C [k] [J]) % MOD ;} // matrix copy void copy (long a [] [2], long B [] [2]) {for (INT I = 0; I <2; ++ I) for (Int J = 0; j <2; ++ J) A [I] [J] = B [I] [J];} // matrix fast power void spow (long N, int mod) {If (n = 1ll) Copy (ANS, mat); else {spow (N/2ll, moD); copy (TEM, ANS); MUL (ANS, TEM, TEM, MoD); If (N % 2ll) {copy (TEM, ANS); MUL (ANS, TEM, mat, MoD) ;}}int main () {int n, m; while (CIN >>n> m) {If (n> 1) {spow (n, 1 <m); cout <ans [0] [1] <Endl;} else cout <0 <Endl;} return 0 ;}
Ultraviolet A 10229-modular Fibonacci