Title
Solution
其实是一个等比数列,可以直接用通项公式。
但是复习了一下矩阵乘法,然后知道了如何正确的构造矩阵乘法中的中间矩阵,之前都是通过不停尝试来构造的。。。
以斐波那契数列为例
f[n] | f[n-1] | |
---|---|---|
f[n-1] | 1 | 0 |
f[n-2] | 1 | 1 |
因为 f [ n ] = f [ n − 1 ] + f [ n − 2 ] f[n]=f[n-1]+f[n-2] f[n]=f[n−1]+f[n−2],所以在第一列都填 1 1 1
所以这道题的中间矩阵
a | 0 |
---|---|
1 | 1 |
因为乘法可能会爆 l o n g l o n g long\ long long long,所以要用龟速乘。
Code
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#define ll long long
#define rep(i,x,y) for(int i=x;i<=y;i++)
using namespace std;
const ll N=3;
ll mod,n,g;
ll tss(ll x,ll y){
ll cnt=0;
for(;y;y>>=1){
if (y&1) cnt=(cnt+x)%mod;
x=(x*2)%mod;
}
return cnt;
}
struct Matrix{
ll w,a[N][N],b[N][N],c[N][N];
void mull(){
memset(c,0,sizeof(c));
rep(i,0,w-1) rep(j,0,w-1) rep(k,0,w-1) c[i][j]=(c[i][j]+tss(a[i][k],a[k][j])%mod)%mod;
memcpy(a,c,sizeof(c));
}
void mul(){
memset(c,0,sizeof(c));
rep(i,0,w-1) rep(j,0,w-1) rep(k,0,w-1) c[i][j]=(c[i][j]+tss(b[i][k],a[k][j])%mod)%mod;
memcpy(b,c,sizeof(c));
}
}M;
ll read(){
ll p=0; char c=getchar();
while (!isdigit(c)) c=getchar();
while (isdigit(c)) p=(p<<3)+(p<<1)+c-48,c=getchar();
return p;
}
int main(){
mod=read(),M.a[0][0]=read(),M.b[0][1]=read(),M.b[0][0]=read(),n=read(),g=read();
M.w=2; M.a[1][0]=M.a[1][1]=1;
for(;n;n>>=1,M.mull()) if (n&1) M.mul();
return 0&printf("%lld",M.b[0][0]%g);
}