【发布时间】:2026-01-17 22:30:01
【问题描述】:
我正在做一个小型密码学程序,需要一个函数来计算功率 mod 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
它并不总是返回错误的答案,所以我不确定为什么会发生这种情况。有什么建议吗?
【问题讨论】:
标签: java cryptography diffie-hellman exponentiation