Description
输入a和b和p,输出(a^b)%p的值
Input
三个整数:
a,b,p (2<=a<=100, 0<=b<=1000000000, 3<=p<=10000)
Output
(a^b)%p的值
Sample Input
2 3 5
Sample Output
3
Hint
a^4=(a^2)*(a^2)
(a*b)%p=((a%p)*(b%p))%p;
Problem Source: ExerciseVI: Adversity leads to prosperity
题解:此题若直接求幂,必然会超时。没关系,我们可用快速幂来规避超时的问题。我们发现,例如,11的二进制表达为:1011。 11%2==1 , 恰好是倒数第一位的数字。5(11/2) %2==1,恰好是倒数第二位的数字。2(5/2)%2==0,恰好是倒数第三位的数……因此我们可以吧a^11分解成a^(2^8+2^1+2^0)。由于要防止中间运算出现溢出错误,因此每步运算都要进行取模。
06.
#include<iostream>
07.
using
namespace
std;
08.
09.
int
main()
10.
{
11.
int
a,b,p;
12.
cin >>a >>b >>p;
13.
int
x=a;
14.
int
result=1;
15.
while
(b)
16.
{
17.
if
(b%2==1)
18.
{
19.
result=((result%p)*(x%p))%p;
20.
}
21.
x=(x%p)*(x%p);
22.
b=b/2;
23.
}
24.
cout <<result <<endl;
25.
}