题解:AT_abc228_e [ABC228E] Integer Sequence Fair
一道不错的数论题,不过题解区讲的都不是很清楚,于是来写一个详细清晰的版本。
先对构成的序列考虑,显然每个位置有
接下来考虑每个序列可以得多少分,因为每个序列可以有
接下来就是考虑如何计算这个值了。
一开始我的做法是直接两个快速幂,代码如下,但是 WA 了。
当时以为是乘法爆 long long 了。但是尝试改用 int128 甚至使用快速乘依然 WA。
typedef long long LL;
const int MOD=998244353;
LL n,k,m;
LL fastpow(LL a,LL n,LL mod){
LL res=1;
while(n){
if(n&1) res=res*a%mod;
a=a*a%mod;
n>>=1;
}
return res;
}
void solve(){
cin>>n>>k>>m;
cout<<fastpow(m,fastpow(k,n,MOD),MOD);
}
后来才想起来其实是因为幂指数取模和结果取模是不一样的。
即
也就是你不能对指数部分直接用快速幂处理,否则结果就变了。
那么你应该想到费马小定理,当
而
接着考虑对
根据带余数除法我们知道一个数
因而,我们的
故
又根据指数运算法则,
又因为
而
不过注意上述使用了费马小定理,是基于
我们需要注意特判
然后你写出了下面这份代码,以为大功告成时,还是 WA 了。
typedef long long LL;
const int MOD=998244353;
LL n,k,m;
LL fastpow(LL a,LL n,LL mod){
LL res=1;
while(n){
if(n&1) res=res*a%mod;
a=a*a%mod;
n>>=1;
}
return res;
}
void solve(){
cin>>n>>k>>m;
if(m%MOD==0) cout<<0;
else cout<<fastpow(m,fastpow(k,n,MOD-1),MOD);
}
注意到快速幂计算时,由于底数很大,乘法可能会爆 long long,因而在快速幂函数中注意对底数取模一下,这样就能 AC 了,代码如下。
typedef long long LL;
const int MOD=998244353;
LL n,k,m;
LL fastpow(LL a,LL n,LL mod){
a%=mod;
LL res=1;
while(n){
if(n&1) res=res*a%mod;
a=a*a%mod;
n>>=1;
}
return res;
}
void solve(){
cin>>n>>k>>m;
if(m%MOD==0) cout<<0;
else cout<<fastpow(m,fastpow(k,n,MOD-1),MOD);
}
当然你也可以一开始就对底数取模,代码如下。
typedef long long LL;
const int MOD=998244353;
LL n,k,m;
LL fastpow(LL a,LL n,LL mod){
LL res=1;
while(n){
if(n&1) res=res*a%mod;
a=a*a%mod;
n>>=1;
}
return res;
}
void solve(){
cin>>n>>k>>m;
m%=MOD,k%=(MOD-1);
if(!m) cout<<0;
else cout<<fastpow(m,fastpow(k,n,MOD-1),MOD);
}