NEUOJ 1391: Big Big Power(费马小定理&快速幂)

费马小定理数论中的一个重要定理,其内容为: 假如p是质数,且(a,p)=1,那么 a^(p-1) ≡1(mod p)。即:假如a是整数,p是质数,且a,p互质,那么a的(p-1)次方除以p的余数恒等于1。稍微变化一下就是(a^b)%p=a^[b%(p-1)]%p。

本题计算a^(b^c)%(1e9+7)先把(b^c)看成整体应用费马小定理有,a^[(b^c)%(1e9+7-1)]=[a^(b^c)]%(1e9+7),然后直接快速幂取模就可以啦!

1391: Big Big Power

时间限制: 1 Sec   内存限制: 256 MB
提交: 168   解决: 25
[ 提交][ 状态][ 讨论版]

题目描述

Calculate the power num a^(b^c) mod 1e9+7

输入

Multiple test cases,each case has three integers a,b and c . a,b,c is less than 1e9;

输出

Output the answer in each line

样例输入

2 3 2

样例输出

512

代码如下:

#include <stdio.h>
#define Mod 1000000007
int exp(int a,int b,int mod)
{
    int ans=1,base=a;
    while(b)
    {
        if(b&1)ans=((long long)ans*base)%mod;
        base=((long long)base*base)%mod;
        b>>=1;
    }
    return ans;
}

int main()
{
    //freopen("input.txt","r",stdin);
    int a,b,c;
    while(~scanf("%d%d%d",&a,&b,&c))
    {
        int n=exp(b,c,Mod-1);
        printf("%d\n",exp(a,n,Mod));
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值