NEUOJ 1391: Big Big Power(费马小定律&快速幂)
NEUOJ 1391: Big Big Power(费马小定理&快速幂)
提交: 168 解决: 25
[提交][状态][讨论版]
费马小定理是数论中的一个重要定理,其内容为: 假如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; }