Link: http://acm.hdu.edu.cn/showproblem.php?pid=2035
人見人愛A^B
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 34363 Accepted Submission(s): 23334
Problem Description
求A^B的最後三位數表示的整數。
說明:A^B的含義是“A的B次方”
Input
輸入數據包含多個測試實例,每個實例佔一行,由兩個正整數A和B組成(1<=A,B<=10000),如果A=0, B=0,則表示輸入數據的結束,不做處理。
Output
對於每個測試實例,請輸出A^B的最後三位表示的整數,每個輸出佔一行。
Sample Input
2 3
12 6
6789 10000
0 0
Sample Output
8
984
1
Author
lcy
Source
ACM程序設計期末考試(2006/06/07)
Recommend
lcy | We have carefully selected several similar problems for you: 1021 2034 1008 2033 1108
解釋:
數的快速冪
A^B <=> (A*A)^(B/2)/*B爲偶數*/ (A*A)^(B/2)*A/*B爲奇數*/
Code
#include <iostream>
#include <cstdio>
using namespace std;
const int mod(1000);
int quick_power(int a,int b)
{
int res=1;
while(b)
{
if(b&1)
res=res*a%mod;
a=a*a%mod;
b>>=1;
}
return res;
}
int main()
{
int a,b;
while(scanf("%d%d",&a,&b),a||b)
{
cout<<quick_power(a,b)<<endl;
}
return 0;
}