Prepared for New Acmer
Description
集训进行了将近2个礼拜,这段时间以恢复性训练为主,我一直在密切关注大家的训练情况,目前为止,对大家的表现相当满意,首先是绝大部分队员的训练积极性很高,其次,都很遵守集训纪律,最后,老队员也起到了很好的带头作用,这里特别感谢为这次DP专题练习赛提供题目和测试数据的集训队队长xhd同学.
特别高兴的是,跟随集训队训练的一批新队员表现非常好,进步也比较显著,特别是训练态度大大超出我的预期,我敢说,如果各位能如此坚持下去,绝对前途无量!
考虑到新队员还没有经过系统训练,我这里特别添加一道简单题:
给定三个正整数A,B和C(A,B,C<=1000000),求A^B mod C的结果.
希望各位都能体会到比赛中AC的快乐,绝对的量身定制,很高的待遇哟,呵呵…
Input
输入数据首先包含一个正整数N,表示测试实例的个数,然后是N行数据,每行包括三个正整数A,B,C。
Output
对每个测试实例请输出计算后的结果,每个实例的输出占一行。
SampleInput
3
2 3 4
3 3 5
4 4 6
SampleOutput
0
2
4
思路
快速幂模板题,如果对快速幂掌握不够就来看看这篇文章 快速幂与矩阵快速幂从0开始
AC代码(递归)
#include<cstdio>
#include<iostream>
using namespace std;
typedef unsigned long long ull;
ull fast_power(ull a,ull b,ull p){
if(b==0) return 1;
a%=p;
ull c=fast_power(a,b>>1,p);//a^(b/2)
if(b&1)//奇数
return c*c%p*a%p;
//偶数
return c*c%p;
}
int main(){
ull a,b,p;
int t;
cin>>t;
while(t--){
cin>>a>>b>>p;
cout<<fast_power(a,b,p)<<endl;
}
return 0;
}
AC代码(非递归)
#include<iostream>
#include<cstdio>
using namespace std;
typedef unsigned long long ull;
ull fast_power(ull a,ull b,ull p){
ull prod=1;
while(b>0){
//当最低二进制位数为1时
if(b&1) prod=prod*a%p;
a=a*a%p;
b>>=1;
}
return prod;
}
int main(){
int t;
ull a,b,p;
cin>>t;
while(t--){
cin>>a>>b>>p;
cout<<fast_power(a,b,p)<<endl;
}
return 0;
}