HDUOJ 5667 Sequence

题目链接~~~

          这个题是关于矩阵快速幂的一道题,只要结合一下费马小定理就可以了。

费马小定理:

                     a ^( p - 1) = 1 (mod p)     p 为素数,且a 与 p互质

这题很明显可以推出f n = a ^( Fn ) ,同样 Fn 也是一个递推式


用公式 :a ^ (Fn % (p - 1)) = (a ^ Fn ) % p 结合矩阵快速幂就可以AC了,注意:a 与 p 不互质的情况。

代码:

#include<cstdio>
#include<iostream>
#include<map>
#include<stack>
#include<string>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std ;
#define LEN sizeof(struct node)
#define LLd long long int
const double PI = 3.1415926 ;
const double INF = 99999999 ;
const int MX =25 ;

LLd mod ;
class M{
  public :
       LLd p[3][3] ;
       M(){
          memset(p ,0 ,sizeof(p)) ;
       }
       void init(){
           for(int i = 0 ;i < 3 ; ++i)
               p[i][i] = 1 ;
       }
       M operator *(const M& a){
          M c ;
          for(int i = 0 ;i < 3 ; ++i)
            for(int k = 0 ;k < 3 ; ++k)
              if(p[i][k])
                 for(int j = 0 ;j < 3 ; ++j)
                    c.p[i][j] = (c.p[i][j] + (p[i][k]*a.p[k][j])%(mod-1))%(mod-1) ;
          return c ;
       }
} ;
M Matrix_Pow(M p ,LLd n){
    M b ;
    b.init() ;
    while(n){
       if(n&1)
          b = b * p ;
       n = n>>1 ;
       p = p * p ;
    }
   return b ;
}
LLd Pow(LLd a ,LLd n){
   LLd b = 1 ;
   while(n){
      if(n&1)
         b = (b*a)%mod ;
      n = n>>1 ;
      a = (a*a)%mod ;
   }
   return b ;
}
int main(){
    LLd T ,n ,a ,b ,c ;
    cin>>T ;
    while(T--){
        cin>>n>>a>>b>>c>>mod ;
        if(n == 1)
            cout<<1<<endl ;
        else if(n == 2)
             cout<<Pow(a ,b)<<endl ;
        else if(a%mod == 0)
             cout<<0<<endl ;
        else {
              M t ;
              t.p[0][0] = c ;
              t.p[0][1] = t.p[1][0] = t.p[2][0] = t.p[2][2] = 1 ;
              M d = Matrix_Pow(t ,n-2) ;
              LLd ans ;
              ans = ((b*d.p[0][0])%(mod-1) + (d.p[2][0]*b)%(mod-1))%(mod-1) ;
              cout<<Pow(a ,ans)<<endl ;
        }
    }
    return 0 ;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Linux猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值