人见人爱A^B
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 47386 Accepted Submission(s): 31673
Problem Description
求A^B的最后三位数表示的整数。
说明:A^B的含义是“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
问题链接:HDU2035 人见人爱A^B
问题简述:计算A^B的最后三位整数。
问题分析:这问题可以用乘方取模函数来解决。
程序说明:增加一个C++语言的版本。
AC的C++语言程序如下:
#include <iostream>
using namespace std;
const int MOD = 1000;
// 快速模幂计算函数
int powermod(long long a, int n, int m)
{
long long res = 1;
while(n) {
if(n & 1) { // n % 2 == 1
res *= a;
res %= m;
}
a *= a;
a %= m;
n >>= 1;
}
return res;
}
int main()
{
int a, b;
while(cin >> a >> b && (a || b))
cout << powermod(a, b, MOD) << endl;
return 0;
}
AC的C语言程序如下:
/*
* 乘方取模
*
* 已知给定的正整数a、n和m,计算x的值,a^n = x (mod m)。
*
* 二分法用在这里也很有效果。
*/
#include <stdio.h>
long powermod(long a, long n, long m)
{
long res = 1L;
while(n) {
if(n & 1L) {
res *= a;
res %= m;
}
a *= a;
a %= m;
n >>= 1;
}
return res;
}
int main(void)
{
long a, n;
for(;;) {
scanf("%ld %ld", &a, &n);
if(a==0 && n==0)
break;
printf("%ld\n", powermod(a, n, 1000L));
}
return 0;
}