Problem 1271 求A^B的最后三位数
【Description】
A^B的含义是“A的B次方” ,1<=A,B<=1000000000。请你编程计算A^B的最后3位数。
【Input】
输入有多个案例。每个案例占一行,每行两个数A、B。当A=0,B=0时表示结束。
【Ouput】
每行对应输出一个结果。
【Sample Input】
2 3
12 6
6789 10000
999999999 999999999
0 0
【Sample Output】
8
984
1
999
【python代码】(部分)
def f(C, E):
N = 1000
D = 1
while E > 0:
if E % 2 == 0:
C = C * C % N
E /= 2
else:
D = D * C % N
E -= 1
return D
def main():
a = int(input())
b = int(input())
print(f(a,b))
main()
【解析】:
注意数据的长度, int 是不够长的,需要用 __int64 或 long long
【C语言】
#include <stdio.h>
__int64 F(__int64 C, __int64 E) {
__int64 N = 1000;
__int64 D = 1;
while (E > 0) {
if (E % 2 == 0) {
C = C * C % N;
E /= 2;
} else {
D = D * C % N;
E -= 1;
}
}
return D;
}
int main() {
__int64 a, b;
while (scanf("%I64d %I64d", &a, &b) != EOF) {
if (a == 0 && b == 0) {
break;
}
printf("%I64d\n", F(a, b));
}
return 0;
}