UVa10692,Huge Mod,数论,欧拉定理,指数循环节

UVa10692,Huge Mod,数论,欧拉定理,指数循环节

// author:latstars
// time:2016-09-02 19:08:11
// 题目:UVa10692,Huge Mod
// 题意:给定一个数组,指定指数运算a[1]^a[2]^a[3]...^a[n]
// 指数运算的计算顺序是从上到下的也就是先计算p=a[2]^a[3]...^a[n]
// 在计算a[1]^p
// 分类:数论,欧拉定理,指数循环节
// 思路:因为a^phi(m)=1 (mod m) m:模数
// 那么就可以利用这条性质p=k*phi(m)+r
// 这里r也就是p mod phi(m)
// 那么a^p=(a^(k*phi(m)))*(a^r)
// 1.当a与m互素的时候
// 前面一部分mod m为1 所以结果只与后面的有关为a^r
// 可以用快速幂来计
// 2.当a与m不互素的时候
// 就要利用指数循环节
// 参考 http://www.xuebuyuan.com/575121.html 的证明
// 而r就是递归调用计算p=a[2]^a[3]...^a[n] mod phi(m) 的结果
// 注意考虑欧拉函数的特殊情况,也就是当a与m不互素的情况
// 指数循环节是指a^p%m=(a^(phi(m)+p%phi(m)))%m
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
const int maxn=20;
typedef long long LL;
LL quickmod(LL a,LL p,LL mod)
{
    LL res=1;
    while(p){
        if(p&1) res=(res*a)%mod;
        a=(a*a)%mod;
        p>>=1;
    }
    return res;
}
LL euler_phi(LL x)
{
    LL res=x;
    for(LL i=2;i*i<=x;i++){
        if(x%i==0){
            res=res/i*(i-1);
            while(x%i==0)
                x/=i;
        }
    }
    if(x>1) res=res/x*(x-1);
    return res;
}
LL cal(LL *a,LL n,LL mod)
{
    if(n==1)    return a[0]%(mod);
    LL r;
    r=cal(a+1,n-1,euler_phi(mod))+euler_phi(mod);
    return quickmod(a[0],r,mod);
}
LL n,m,a[maxn];
void solve(void)
{
    LL res=cal(a,n,m);
    cout<<res<<endl;
}
int main()
{
    // freopen("out.txt","w",stdout);
    int t=1;
    while(cin>>m>>n){
        for(int i=0;i<n;i++)
            cin>>a[i];
        printf("Case #%d: ",t++);
        solve();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值