东大OJ-1391-Big big Power

题目描述

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



    需要用到费马小定理.如果p是质数,并且a不等于1且a不等于p,那么   a^(p-1)%p====1.
所以,a^1000000006   %  1000000007=1.

a^b^c%1000000007=a^(b^c % 1000000006) % 1000000007.
这是第一关.用费马小定理将问题化简一下.
第二关是快速幂,用递归实现特别清晰.

九指神丐洪七公曾经告诉郭靖:遇到敌人不要把注意力放在敌人出什么招数上,你只需要把这降龙十八掌一遍一遍的使将出来,必可立于不败之地.
管他是否多余,多用long long int.各种取余.
为了安全,可以适当的冗余.尤其是现在的大程序.



#include<iostream>
using namespace std;
long long int go(long long int a, long long int b, long long int c){
	if (b == 0)return 1;
	long long int t = go(a, b / 2, c);
	long long int p = (t*t) % c;
	if (b % 2 == 0)return p;
	return (p*a) % c;
}
int main(){
	//freopen("in.txt", "r", stdin);
	long long int a, b, c;
	while (cin >> a >> b >> c)
		cout << go(a, go(b, c, 1000000006), 1000000007)<<endl;
	return 0;
}


原文地址:https://www.cnblogs.com/weiyinfu/p/5013909.html