UVa 10229 Modular Fibonacci: Matrix fast Power seeking Fibonacci

Source: Internet
Author: User
Tags time limit


10229-modular Fibonacci



Time limit:3.000 seconds



Http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=115&page=show_ problem&problem=1170



The Fibonacci numbers (0, 1, 1, 2, 3, 5, 8, ...) are defined by the recurrence:



F0 = 0 F1 = 1 Fi = Fi-1 + Fi-2 for i>1



Write a program which calculates Mn = Fn mod 2m for given pair of N and M. 0< =n< and =2147483647 20. Note This a mod B gives the remainder when a was divided by B.



Input and Output



Input consists of several lines specifying a pair of N and M. Output should Mn, one per line.



Sample Input


7
11 6


Sample Output


25


Ideas:






As shown above, use the matrix fast power to fix.



Note: (1<<19) ^2 will be super int, so use long long



Complete code:


/*0.015s*/
     
#include<cstdio>  
#include<cstring>  
typedef long long ll;  
     
ll mod;  
     
struct mat  
{  
    ll v[2][2];  
    mat()  
    {  
        memset(v, 0, sizeof(v));  
    }  
} m1;  
     
mat operator * (mat a, mat b)  
{  
    mat c;  
    for (int i = 0; i < 2; i++)  
        for (int j = 0; j < 2; j++)  
            for (int k = 0; k < 2; k++)  
                c.v[i][j] = (c.v[i][j] + a.v[i][k] * b.v[k][j]) % mod;  
    return c;  
}  
     
inline mat quickpow(mat a, int k)  
{  
    mat b;  
    b.v[0][0] = b.v[1][1] = 1;  
    while (k)  
    {  
        if (k & 1)  
            b = b * a;  
        k >>= 1;  
        a = a * a;  
    }  
    return b;  
}  
     
int main()  
{  
    m1.v[0][0] = m1.v[0][1] = m1.v[1][0] = 1, m1.v[1][1] = 0;  
    int n, m;  
    while (~scanf("%d%d", &n, &m))  
    {  
        if (n == 0 || m == 0) puts("0");  
        else
        {  
            mod = 1 << m;  
            printf("%d\n", quickpow(m1, n - 1).v[0][0]);  
        }  
    }  
    return 0;  
}


See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/


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.