Matrix 10 questions [6] poj3070 Fibonacci

Source: Internet
Author: User

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 ;}}




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.