您的位置:首页 > 其它

UVA10692:Huge Mods

2018-01-19 20:23 309 查看

题面

传送门

题意

输入正整数a1,a2,a3..an和模m,求a1^a2^…^an mod m

Sol

首先有ab≡⎧⎩⎨⎪⎪ab%ϕ(p) gcd(a,p)=1ab gcd(a,p)≠1,b<ϕ(p)ab%ϕ(p)+ϕ(p) gcd(a,p)≠1,b≥ϕ(p) (mod p)

递归处理,每次取φ,可以试乘来判断是否会大于φ大于时加上就好了

# include <bits/stdc++.h>
# define RG register
# define IL inline
# define Fill(a, b) memset(a, b, sizeof(a))
using namespace std;
typedef long long ll;

IL ll Read(){
RG ll x = 0, z = 1; RG char c = getchar();
for(; c < '0' || c > '9'; c = getchar()){
if(c == '#') exit(0);
z = c == '-' ? -1 : 1;
}
for(; c >= '0' && c <= '9'; c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);
return x * z;
}

int n, m, a[20];

IL int Phi(RG int x){
RG int cnt = x;
for(RG int i = 2; i * i <= x; ++i){
if(x % i) continue;
while(!(x % i)) x /= i;
cnt -= cnt / i;
}
if(x > 1) cnt -= cnt / x;
return cnt;
}

IL int Pow(RG ll x, RG ll y, RG ll p){
RG int flg2 = 0, flg1 = 0; RG ll cnt = 1;
for(; y; y >>= 1){
if(y & 1) flg1 |= (cnt * x >= p || flg2), cnt = cnt * x % p;
flg2 |= (x * x >= p); x = x * x % p;
}
return cnt + flg1 * p;
}

IL int Calc(RG int x, RG int p){
if(x == n) return Pow(a[x], 1, p);
return Pow(a[x], Calc(x + 1, Phi(p)), p);
}

int main(RG int argc, RG char* argv[]){
for(RG int Case = 1; ; ++Case){
m = Read(); n = Read();
printf("Case #%d: ", Case);
for(RG int i = 1; i <= n; ++i) a[i] = Read();
printf("%d\n", Calc(1, m) % m);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: