//快速求a^b%m
```cpp
#include <stdio.h>
typedef long long LL;
LL pow(LL a, LL b, LL m){
LL ans = 1;
for(int i = 0; i < b; i++){
ans = ans * a % m;
}
return ans;
}
int BinaryPow(int a, int b, int m){
if(b == 0) return 1;
if(b % 2 == 1){
return a * BinaryPow(a, b - 1, m) % b;//
//this should be
//return a * BinaryPow(a, b - 1, m) % m;
}
else{
int mul = BinaryPow(a, b / 2, m);
return mul * mul % m;
}
}
int main()
{
int a, b, m;
scanf("%d%d%d", &a, &b, &m);
printf("%d\n", BinaryPow(a, b, m));
return 0;
}
我就说为什么输入什么,输出都是0.原来m打成了b。
结果找了好久的问题,下次要注意啊!!
本文深入探讨了快速求a^b%m的算法实现,包括常见的迭代法和递归二进制快速幂方法。通过一个具体的编程实例,指出并修正了一个容易忽视的代码错误,即在取模运算中误将模数m写为b,导致程序输出始终为0的bug。此外,文章强调了在调试过程中仔细检查变量名的重要性。
314

被折叠的 条评论
为什么被折叠?



