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

题意:给出一个数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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值