hdoj 5667 Sequence(矩阵快速幂、费马小定理)

看着就像是要用矩阵做,但是有个a^b,不知道怎么去推递推式。


思路:对两边取a为底的对数,就可以得到


loga(fn) = c*loga(fn-1) + loga(fn-2) + b,然后令Fn = loga(fn), 


可以得到Fn = c*Fn-1 + Fn-2 + b


之后构造矩阵快速幂就行了,得到Fn, fn = a^(Fn), 要mod p,指数


又特别大,所以需要用到费马小定理了(a^x≡a^(x%(p-1))(mod p)).


看到有人说需要加个特判, a是p的倍数时应该输出0。但测试数据没有a事p的倍数,所以

不加也没事。


参考博客:点击打开链接


代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll n, a, b, c, p;

struct node
{
    ll s[3][3];
    node() { memset(s, 0, sizeof(s)); }
};

node mul(node a, node b)
{
    node t;
    for(int i = 0; i < 3; i++)
        for(int j = 0; j < 3; j++)
            for(int k = 0; k < 3; k++)
                t.s[i][j] = (t.s[i][j]+a.s[i][k]*b.s[k][j])%(p-1);
    return t;
}

node mt_pow(node p, ll k)
{
    node q;
    for(int i = 0; i < 3; i++) q.s[i][i] = 1;
    while(k)
    {
        if(k&1) q = mul(p, q);
        p = mul(p, p);
        k /= 2;
    }
    return q;
}

ll po(ll x, ll y)
{
    ll ans = 1;
    while(y)
    {
        if(y&1) ans = (ans*x)%p;
        x = x*x%p;
        y /= 2;
    }
    return ans;
}

int main(void)
{
    int t;
    cin >> t;
    while(t--)
    {
        scanf("%lld%lld%lld%lld%lld", &n, &a, &b, &c, &p);
        if(n == 1) puts("1");
        else if(a % p == 0) puts("0");
        else
        {
            node base;
            base.s[0][0] = c; base.s[0][1] = 1;
            base.s[0][2] = 1; base.s[1][0] = 1;
            base.s[2][2] = 1;

            node ans = mt_pow(base, n-2);
            ll P = (ans.s[0][0]+ans.s[0][2])*b%(p-1);
            printf("%lld\n", po(a, P)%p);
        }
    }
    return 0;
}


Sequence

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1587    Accepted Submission(s): 537


Problem Description
     Holion August will eat every thing he has found.

     Now there are many foods,but he does not want to eat all of them at once,so he find a sequence.

fn=1,ab,abfcn1fn2,n=1n=2otherwise

     He gives you 5 numbers n,a,b,c,p,and he will eat  fn  foods.But there are only p foods,so you should tell him  fn  mod p.
 

Input
     The first line has a number,T,means testcase.

     Each testcase has 5 numbers,including n,a,b,c,p in a line.

    1T10,1n1018,1a,b,c109 , p  is a prime number,and  p109+7 .
 

Output
     Output one number for each case,which is  fn  mod p.
 

Sample Input
  
  
1 5 3 3 3 233
 

Sample Output
  
  
190
 

Source
 

Recommend
wange2014   |   We have carefully selected several similar problems for you:   5981  5980  5979  5978  5977 



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值