hdu-4565(矩阵快速幂+推导)

问题描述:

A sequence S n is defined as:Sn=[(a+sqrt(b))^(n)] % m,其中[ ] 表示向下取整.

Input

 There are several test cases, each test case in one line contains four positive integers: a, b, n, m. Where 0< a, m < 2 15, (a-1) 2< b < a 2, 0 < b, n < 2 31.The input will finish with the end of file

Output

For each the case, output an integer S n.

Sample Input

2 3 1 2013
2 3 2 2013
2 2 1 2013
Sample Output

4
14
4

题目题意;题目给我们a,b,n,m让我们求Sn %m.

题目分析:这道题目与hdu_2256很像,这是是那道题目的链接点击打开链接

这道题目,我也按照以前的方法再推导一遍;


答案就推导出来了。

代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#define ll long long
using namespace std;

ll a,b,n,mod;
struct matrix
{
    ll f[3][3];
    matrix operator * (const matrix &a) const {
        matrix res;
        for (int i=1;i<=2;i++) {
            for (int j=1;j<=2;j++) {
                res.f[i][j]=0;
                for (int k=1;k<=2;k++)
                    res.f[i][j]=(res.f[i][j]+(*this).f[i][k]*a.f[k][j])%mod;
            }
        }
        return res;
    }
}A,B;

matrix fast_pow(matrix base,int k)
{
    matrix ans=base;
    while (k) {
        if (k&1)
            ans=ans*base;
        base=base*base;
        k>>=1;
    }
    return ans;
}

void init()
{
    B.f[1][1]=a,B.f[1][2]=b;
    B.f[2][1]=1,B.f[2][2]=a;
    A.f[1][1]=a,A.f[2][1]=1;
}

int main()
{
    while (scanf("%lld%lld%lld%lld",&a,&b,&n,&mod)!=EOF) {
        if (n==1) { printf("%lld\n",(a+(ll) sqrt(b)+1)%mod);continue;}
        n-=2;
        init();
        struct matrix cur,ans;
        cur=B;
        cur=fast_pow(cur,n);
        ans=cur*A;
        printf("%lld\n",(2*ans.f[1][1])%mod);

    }
    return 0;
}

















  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值