hdu 4549 M斐波那契数列

简介:

click here ~~

Problem Description
M斐波那契数列F[n]是一种整数数列,它的定义如下:

F[0] = a
F[1] = b
F[n] = F[n-1] * F[n-2] ( n > 1 )

现在给出a, b, n,你能求出F[n]的值吗?


Input
输入包含多组测试数据;
每组数据占一行,包含3个整数a, b, n( 0 <= a, b, n <= 10^9 )


Output
对每组测试数据请输出一个整数F[n],由于F[n]可能很大,你只需输出F[n]对1000000007取模后的值即可,每组数据输出一行。

题目大意:这是中文。。。。

解题思路:采用斐波那契的思想,就是求一个f(n) % mod;
f(0) = a, f(1) = b;
f(n) = f(n-1)*f(n-2);
最后化为f(n) = ((a^x)*(b^y)) %mod;
而x与y是斐波那契数,而且mod是素数;
所以根据公式:a^b%c == a^(b %phi(c)+phi(c))%c;

又因为c是素数所以直接化为:
a^b%c == a^(b %(c-1))%(c-1);

上代码:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

const int mod = 1e9 + 7;
const int maxn = 2;

typedef long long LL;

struct Matrix
{
    LL m[maxn][maxn];
};
///单位阵
Matrix I = {1, 0,
            0, 1
           };
///目标阵           
Matrix P = {0, 1,
            1, 1
           };
///矩阵乘法           
Matrix matrix_mul(Matrix a, Matrix b)
{
    int i, j, k;
    Matrix c;
    for(i=0; i<maxn; i++)
    {
        for(j=0; j<maxn; j++)
        {
            c.m[i][j] = 0;
            for(k=0; k<maxn; k++)
                c.m[i][j] += (a.m[i][k] * b.m[k][j]) % (mod-1);
            c.m[i][j] %= (mod-1);
        }
    }
    return c;
}
///矩阵快速幂
Matrix quick_M(LL m)
{
    Matrix ans = I, b = P;
    while(m)
    {
        if(m & 1)
            ans = matrix_mul(ans, b);
        m >>= 1;
        b = matrix_mul(b, b);
    }
    return ans;
}
///快速幂
LL quick_m(LL a, LL b)
{
    LL ans = 1;
    LL tmp = a%mod;
    while(b)
    {
        if(b & 1)
        {
            ans *= tmp;
            ans %= mod;
        }
        tmp *= tmp;
        tmp %= mod;
        b >>= 1;
    }
    return ans;
}

int main()
{
    int a, b, n;
    while(~scanf("%d%d%d",&a,&b,&n))
    {
        Matrix p = quick_M(n);
        int ans = (quick_m(a,p.m[0][0]) * quick_m(b,p.m[1][0]))%mod;
        cout<<ans<<endl;
    }
    return 0;
}
/**
Sample Input

0 1 0
6 10 2


Sample Output

0
60
**/
目录
相关文章
|
5月前
hdu1406 完数 (水题)
hdu1406 完数 (水题)
27 0
AcWing 741. 斐波那契数列
AcWing 741. 斐波那契数列
72 0
AcWing 741. 斐波那契数列
AcWing 21. 斐波那契数列
AcWing 21. 斐波那契数列
82 0
AcWing 21. 斐波那契数列
HDU 4283 You Are the One(动态规划)
HDU 4283 You Are the One(动态规划)
44 0
HDU 4283 You Are the One(动态规划)
HDU-1058,Humble Numbers(丑数打表)
HDU-1058,Humble Numbers(丑数打表)
|
C++ 人工智能 BI
HDU2032杨辉三角
有点强迫症,主函数必须简洁,但是这里的if判断语句很碍眼,自己也并没有想到什么不画蛇添足的方法使代码更加简洁......
1478 0
|
Java
HDU 1021 Fibonacci Again
Fibonacci Again Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 58267    Accepted Submission(...
889 0
【HDU 4451 Dressing】水题,组合数
有衣服、裤子、鞋数量分别为n,m,k,给出p对不和谐的衣-裤或裤-鞋搭配,问一共有多少种和谐的衣裤鞋的搭配。 全部的组合有Cn1Cm1Ck1种。 设p对中有p1对衣-裤,p2对裤-鞋,则不和谐的搭配共有p1*Ck1+p2*Cn1种,但有被重复计算两次的搭配共p3对,它们引用了同一裤。
884 0