Uva10299-modular Fibonacci (Fibonacci series + matrix fast power)

Source: Internet
Author: User

Question Link


Give N and M, and find F (n) % m. f (x) is the Fibonacci sequence.

Idea: Because N is big, it is very likely that it will use the formula to calculate it, so we can use the Matrix to quickly solve the power. | (1, 1), (1, 0) | * | f (n-1), F (n-2) | = | f (N), F (n-1) |, so f (N) equivalent to | F (1), F (0) | multiplied by N-1 | (1, 1), (1, 0) |.

Code:

#include <iostream>#include <cstdio>#include <cstring>#include <cmath>#include <algorithm>typedef long long ll;using namespace std;ll n, p, k;int m;struct mat{    ll s[2][2];    mat(ll a = 0, ll b = 0, ll c = 0, ll d = 0) {        s[0][0] = a;         s[0][1] = b;         s[1][0] = c;         s[1][1] = d;     }}c(1, 1, 1, 0), tmp(1, 0, 0, 1);mat operator * (const mat& a, const mat& b) {    mat Mat;    for (int i = 0; i < 2; i++)        for (int j = 0; j < 2; j++)            Mat.s[i][j] = (a.s[i][0] * b.s[0][j] + a.s[i][1] * b.s[1][j]) % p;    return Mat; }mat pow_mod(ll k) {    if (k == 0)        return tmp;    else if (k == 1)        return c;    mat a = pow_mod(k / 2);    a = a * a;    if (k % 2)        a = a * c;    return a;}int main() {    while (scanf("%lld%d", &n, &m) != EOF) {        p = pow(2, m);         if (n) {            mat ans = pow_mod(n - 1);             k = ans.s[0][0];        }          else            k = 0;        printf("%lld\n", k);    }     return 0;}


Uva10299-modular Fibonacci (Fibonacci series + matrix fast power)

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.