我试图在 java 中运行一些椭圆曲线结果,但模运算符似乎没有输出正确的结果。
int a = 17;
double previousx = 4;
double previousy = 14;
double xnew;
double ynew;
double sigma;
double convert;
for (int i = 1; i < 10; i++) {
convert = 0;
for (int j = 0; i<60; j++) {
if (((2 * previousy * j) % 59) == 1) {
convert = j;
break;
}
}
sigma = ((3 * Math.pow(previousx, 2) + a) * convert) % 59;
xnew = ((sigma * sigma) - (2 * previousx)) % 59;
ynew = (sigma * (previousx - xnew) - previousy) % 59;
System.out.println((Math.pow(2, i)) + "x P: " + xnew + "," + ynew + " Sigma:" + sigma);
previousx = xnew;
previousy = ynew;
}
第一次迭代的输出:
2.0x P: 8.0,-57.0 Sigma:55.0
8 和 55 是正确的,但是 -57 mod 59 = 2 而不是 -57。我该如何解决这个问题?
最佳答案
8 and 55 are correct, but -57 mod 59 = 2 and not -57. How do I fix this?
Java 中的 %
运算符不是模数 - 它是 remainder operator .根据语言规范,它的行为完全正确。当您怀疑 Java 行为不当时,总是值得检查规范以查看它是否真的是您的期望不正确。
如果你想要模运算符,你只需要检查结果是否为负,如果是则再次添加除数:
int remainder = (2 * previousy * j) % 59;
int modulus = remainder < 0 ? remainder + 59 : remainder;
if (modulus == 1) {
...
}
或者,在您的情况下:
int remainder = (2 * previousy * j) % 59;
if (remainder == 1 || remainder == -58) {
...
}
...当然,还要适当调整 %
的其余用法。
此外,正如 Stijn de Witt 所提到的,您的内部循环条件中似乎有错字。
关于java - Java 中不正确的模数结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22285579/