如何解决Java幂指数方法不断返回错误值
我正在做一个小型加密程序,需要一个函数来计算幂模 n
我写了这个方法:
static int power(int x,int y,int p){
int res = 1; // Initialize result
x = x % p; // Update x if it is more than or equal to p
while (y > 0) {
res = ((res*x) % p)+p % p;
y-=1;
}
return res;
}
但我注意到它在某些情况下返回错误的答案。示例:
56295^779 mod 69997 应该返回 53580 但返回 20366
43576^7116 mod 50087 应该返回 35712 但返回 40613
它并不总是返回错误的答案,所以我不确定为什么会发生这种情况。有什么建议吗?
解决方法
你是整数溢出的受害者。
res = ((res*x) % p)+p % p;
此行可能会溢出。 res * x 不能保证适合有符号的 32 位整数(但确实适合有符号的 64 位整数)。
示例:
2147483647 * 2 = -2
1147483647 * 22 = -525163542
为防止这种情况发生,您可以将 res 设为 long
而不是 int
,然后在从函数返回时转换回 int
。
static int power(int x,int y,int p){
long res = 1; // Initialize as long to prevent overflow!
x = x % p;
while (y > 0) {
res = ((res*x) % p)+p % p; // No more overflow here!
y-=1;
}
return (int) res; // Cast result back to int
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。