我在我的一个程序中使用了以下函数。
我试图确保我的代码高效,但是我在网上找不到任何帮助来告诉我如何识别可以改进的地方...
有没有人可以帮助确定是否有任何部分我可以改进(更快)或更有效地运行
z、s和t都是整数
powerMod(z, s, t) {
int temp = 1;
while (s > 0) {
temp = temp * z;
s = s - 1;
}
temp = temp mod t;
return temp;
}
所以它的整体功能也是计算 z 的 s 次方,然后每次将其除以 n。非常简单,但我不知道如何使其更快,因为它将被主程序使用数百或数千次
最佳答案
所以有这样的事情吗?
使用exponentiation by square我使用了 long 以防由于 int * int...
int powMod(int z, int s, int t){
long result = 1; //int * int will never exceed the size of a long
long multiplicant = z;
while(s > 0){
if(s % 2 == 1) {
result *= multiplicant;
result %= t; // do modulo on each temporary result to keep accuracy
}
multiplicant *= multiplicant;
multiplicant %= t;
s /= 2;
}
return result;
}
关于Java 高效改进代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27526979/