Icebound and Sequence
分析:
1、等比数列求和 mod p 因为不能保证 p 是素数,所以不能对(q-1)求逆元 .. 法一终..(待补)
-------------------------------------------- 哦吼吼~ 如果有下面的公式,那不就不用求逆元啦~ 但是需要注意快速幂可能会爆long long...所以加个快速乘...解决
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll q,n,p;
ll mulit(ll x,ll y) { ///p=p*(q-1) 直接用快速幂会爆ll
ll cnt=0;
while(y) {
if(y&1)
cnt=(cnt+x)%p;
x=2*x%p;
y>>=1;
}
return cnt;
}
ll pow(ll x,ll y,ll mod) {
ll ans=1;
while(y) {
if(y&1)
ans=mulit(ans,x)%mod;///需要快速乘
y>>=1;
x=mulit(x,x)%mod;
}
return ans;
}
int main() {
int t;
cin>>t;
while(t--) {
cin>>q>>n>>p;
p=(q-1)*p;
ll ans=(pow(q,n+1,p)-q+p)%p/(q-1);
cout<<ans<<endl;
}
return 0;
}
2、用二分方法,递归搜索,举个栗子:
当项数 n 为偶数: = = 其中 mid =(1+n) / 2;
当项数 n 为奇数: = = ....
CODE:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll q,n,p;
ll pow(ll x,ll y,ll mod) {
ll ans=1;
while(y) {
if(y&1)
ans=ans*x%mod;
y>>=1;
x=x*x%mod;
}
return ans;
}
ll solve(ll r,ll u,ll mod) {
if(r==1)return u%mod;
int mid=(r+1)>>1;
if(r%2==0)
return ((pow(u,mid,mod)+1)*solve(mid,u,mod)%mod)%mod;
else
return (pow(u,mid,mod)+(pow(u,mid,mod)+1)*solve(mid-1,u,mod)%mod)%mod;
}
int main() {
int t;
cin>>t;
while(t--) {
cin>>q>>n>>p;
if(q==1)cout<<n%p<<endl;
else cout<<solve(n,q,p)<<endl;
}
return 0;
}