Uva-10229-modular Fibonacci (Matrix fast Power + Fibonacci)

Source: Internet
Author: User

Topic Transfer: UVA-10229

Idea: The simple matrix quickly powers the Fibonacci sequence, then notice that the intermediate result can explode int, because 2^19 has more than 500,000

AC Code:

#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include < cmath> #include <queue> #include <stack> #include <vector> #include <map> #include <set > #include <deque> #include <cctype> #define LL long long#define INF 0x7fffffffusing namespace Std;int mp[20 ]; LL N, m;void init () {mp[0] = 1;for (int i = 1; i <; i + +) {Mp[i] = 2 * mp[i-1];}} struct Matrix {LL m[2][2];}; Matrix Ans;matrix base = {1, 1, 1, 0};matrix multiply (matrix A, matrix B, LL MOD) {matrix ret;for (int i = 0; i < 2; i +  +) {for (int j = 0; J < 2; J + +) {Ret.m[i][j] = 0;for (int k = 0; k < 2; k + +) {Ret.m[i][j] = (Ret.m[i][j] + a.m[i][k) * B.m[k][j])% MOD;}}} return ret;} LL Kmod (Matrix A, ll N, ll MOD) {Matrix ans = {1, 0, 0, 1};while (n) {if (n & 1) ans = multiply (ans, a, mod); a = Multipl Y (A, A, MOD); n >>= 1;} return ans.m[0][1];} int main () {init (); while (Cin >> n >> m) {cout << kmod (base, N, Mp[m]) &Lt;< Endl;} return 0;}

Uva-10229-modular Fibonacci (Matrix fast Power + Fibonacci)

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.