此题涉及一个非常重要的算法:二分求幂。相对不好理解,消化如下:
关于二分求幂的原理见下图:
a^b,基本的思想是将b进行二进制转化。所以代码的主体是在b的二进制化的while循环上进行改造:
while (b>0){
if (b%2==1){
ans*=weight;
}
b/=2;
weight*=weight;
}
加红部分为二进制化的代码。故二分求幂的代码主体就是在做三件事:
①b%2,b/2 //指数二进制化
②weight*=weight //计算二进制化后的指数的该位权重
③ans*=pow //将此位的计算结果累乘到最终结果上
完整代码如下:
#include <iostream>
using namespace std;
int main(){
int a,b;
int weight,ans;
while (cin>>a>>b,a||b){
//initiate
weight=a;
ans=1;
//calculate
while (b>0){
if (b%2==1){
ans*=weight;
ans%=1000;//结果只需最后三位
}
b/=2;
weight*=weight;
weight%=1000;//结果只需最后三位
}
//output
cout<<ans<<endl;
}
return true;
}
-
题目地址:点击打开链接
题目描述:
-
求A^B的最后三位数表示的整数。说明:A^B的含义是“A的B次方”
-
输入:
-
输入数据包含多个测试实例,每个实例占一行,由两个正整数A和B组成(1<=A,B<=10000),如果A=0, B=0,则表示输入数据的结束,不做处理。
-
输出:
-
对于每个测试实例,请输出A^B的最后三位表示的整数,每个输出占一行。
-
样例输入:
-
2 3 12 6 6789 10000 0 0
-
样例输出:
-
8 984 1