简体   繁体   English

Java中不正确的模结果

[英]Incorrect modulo results in Java

I'm trying to run some elliptic curve results in java, but the modulo operator doesn't seem to output the right results. 我正在尝试在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;
}

output of the first iteration: 第一次迭代的输出:

2.0x P: 8.0,-57.0 Sigma:55.0 2.0倍P:8.0,-57.0西格玛:55.0

8 and 55 are correct, but -57 mod 59 = 2 and not -57. 8和55是正确的,但-57 mod 59 = 2而不是-57。 How do I fix this? 我该如何解决?

8 and 55 are correct, but -57 mod 59 = 2 and not -57. 8和55是正确的,但-57 mod 59 = 2而不是-57。 How do I fix this? 我该如何解决?

The % operator in Java isn't modulus - it's the remainder operator . Java中的%运算符不是模数-它是余数运算符 It's behaving entirely correctly according to the language specification. 根据语言规范,它的行为完全正确。 When you suspect that Java is misbehaving, it's always worth checking the specification to see whether it's actually your expectations which are incorrect. 当您怀疑Java的行为异常时,总是值得检查一下规范,以查看实际上是否是您的期望不正确。

If you want a modulus operator, you just need to check whether the result is negative, and if so add the divisor again: 如果需要模运算符,则只需检查结果是否为负数,如果是,则再次添加除数:

int remainder = (2 * previousy * j) % 59;
int modulus = remainder < 0 ? remainder + 59 : remainder;
if (modulus == 1) {
    ...
}

Alternatively, in your case: 或者,在您的情况下:

int remainder = (2 * previousy * j) % 59;
if (remainder == 1 || remainder == -58) {
    ...
}

... and adjust the rest of your uses of % as appropriate too, of course. ...当然也要适当调整%的其余用途。

Additionally, as Stijn de Witt mentioned, it looks like you've got a typo in your inner loop condition. 此外,正如Stijn de Witt所提到的,看起来您的内循环条件有错别字。

It looks to me like you have a typo in the inner loop: 在我看来,您在内部循环中有错别字:

for (int j = 0 ; i<60 ; j++)

It says i <60 in a loop that is iterating over j... 它说 <60在一个遍历j的循环中...

I'd try fixing that. 我会尝试修复该问题。

As to the original question... Can you reduce your test case? 关于原始问题...您可以减少测试用例吗? If you maintain that modulo is not working correctly for some numbers then why not make a single statement that does a modulo on those numbers and prints the results? 如果您认为某些数字的取模不正确,那为什么不做一个对这些数字取模并输出结果的语句呢?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM