Question link: http://poj.org/problem? Id = 3070
Given N and 10000, calculate the value of MOD 10000 in the n-th Fibonacci number. N cannot exceed 2 ^ 31. The result is retained with four digits.
A simple question is much easier than what I have done before.
Construct the simplest Fibonacci matrix.
# Include <iostream> # include <cstring> # include <stdio. h> using namespace STD; const int max = 2; struct matrix {int V [Max] [Max] ;}; int n = 2, M = 10000; matrix mtadd (matrix A, matrix B) // evaluate matrix A + B {int I, j; matrix C; for (I = 0; I <n; I ++) for (j = 0; j <n; j ++) C. V [I] [J] = (. V [I] [J] + B. V [I] [J]) % m; return C;} matrix mtmul (matrix A, matrix B) // evaluate matrix A * B {int I, J, K; matrix C; for (I = 0; I <n; I ++) for (j = 0; j <n; j ++) {C. V [I] [J] = 0; For (k = 0; k <n; k ++) C. V [I] [J] = (. V [I] [k] * B. V [k] [J] + C. V [I] [J]) % m;} return C;} matrix mtpow (matrix origin, int K) // matrix fast power {int I; matrix res; memset (res. v, 0, sizeof (res. v); for (I = 1; I <= N; I ++) res. V [I] [I] = 1; while (k) {If (K & 1) RES = mtmul (Res, origin); origin = mtmul (origin, origin ); k> = 1;} return res;} void out (matrix A) {for (INT I = 0; I <n; I ++) {for (Int J = 0; j <N; j ++) cout <. V [I] [J] <"; cout <Endl;} matrix mtcal (matrix A, int K) // evaluate S (k) = a + A2 + A3 +... + AK {If (k = 1) return a; matrix B = mtpow (A, (k + 1)/2); matrix C = mtcal (, k/2); If (K % 2 = 0) return mtmul (mtadd (mtpow (A, 0), B), c); // such as S (6) = (1 + a ^ 3) * s (3 ). Else return mtadd (A, mtmul (mtadd (a, B), c); // such as S (7) = a + (a + A ^ 4) * s (3)} int main () {int num; while (~ Scanf ("% d", & num) {If (num =-1) break; matrix A;. V [0] [0] = 1;. V [0] [1] = 1;. V [1] [0] = 1;. V [1] [1] = 0; matrix ans = mtpow (A, num); // out (ANS); cout <ans. V [1] [0] <Endl ;}}