您的位置:首页 > 其它

uva 10692 - Huge Mods(指数循环节)

2013-10-04 18:58 351 查看
题意:给出一个数m,和n个数a1~an 求a1^a2^a3...^an%m 的值

解析: 用欧拉函数求解 ,有公式:

A^x % m = A^(x%phi(m)+phi(m)) % m (x >= phi(m))


证明:http://hi.baidu.com/aekdycoin/item/e493adc9a7c0870bad092fd9

#include<iostream>
#include<cstdio>
#include<math.h>
#include<string.h>
using namespace std;
#define N 10005
typedef long long LL;
LL a[20];
LL euler(LL n)
{
LL res=n;
LL m=(LL)sqrt(n+0.5);
for(LL i=2; i<=m; i++)
{
if(n%i==0)
{
res=res/i*(i-1);
while(n%i==0) n/=i;
}
}
if(n>1) res=res/n*(n-1);
return res;
}
LL pow(LL a,LL n,LL m)
{
LL r=1,p=a;
while(n)
{
if(n&1) r=(r*p)%m;
p=(p*p)%m;
n>>=1;
}
return r;
}

LL solve(LL c,LL n,LL m)
{
if(c==n-1) return a[c]%m;
LL temp=solve(c+1,n,euler(m));
LL ans=pow(a[c],temp+euler(m),m);
return ans;
}

int main()
{
int i,j,t=1;
LL n,m;
string s;
while(cin>>s&&s!="#")
{
m=0;
for(i=0; i<s.length(); i++)
m=m*10+(s[i]-'0');
scanf("%lld",&n);
for(i=0; i<n; i++)
scanf("%lld",&a[i]);
printf("Case #%d: %lld\n",t++,solve(0,n,m)%m);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: