题目链接:http://codeforces.com/problemset/problem/17/D
求(b-1)bn-1%c,对bn-1用欧拉降幂。如果模c之后为0,答案不是0,是c
#include<iostream> #include<cmath> using namespace std; #define ll long long ll gcd(ll a,ll b) { return b?gcd(b,a%b):a; } ll phi(ll x) { ll ret=x,a=x; for(ll i=2;i*i<=a;i++) { if(a%i==0)ret=ret/i*(i-1); while(a%i==0)a/=i; } if(a>1)ret=ret/a*(a-1); return ret; } ll poww(ll a,ll b,ll mod) { ll ret=1; while(b) { if(b&1)ret=ret*a%mod; a=a*a%mod; b>>=1; } return ret; } ll getNum(string s,ll mod) { ll ret=0,len=s.size(); for(int i=0;i<len;i++) ret=(ret*10+s[i]-'0')%mod; return ret; } int main() { string b,n; ll c; cin>>b>>n>>c; ll bb=getNum(b,c),ph=phi(c),d=gcd(bb,c),ans; if(n.size()<10) { ll nn=getNum(n,1ll*1e15)-1; if(d==1)ans=((bb-1+c)%c)*poww(bb,nn%ph,c)%c; else { if(nn<ph)ans=((bb-1+c)%c)*poww(bb,nn,c)%c; else ans=((bb-1+c)%c)*poww(bb,nn%ph+ph,c)%c; } } else { ll nn=(getNum(n,ph)-1+ph)%ph; if(d==1)ans=((bb-1+c)%c)*poww(bb,nn,c)%c; else ans=((bb-1+c)%c)*poww(bb,nn+ph,c)%c; } if(ans)cout<<ans<<endl; else cout<<c<<endl; return 0; }