I'm trying to run some elliptic curve results in java, but the modulo operator doesn't seem to output the right results.
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
8 and 55 are correct, but -57 mod 59 = 2 and not -57. How do I fix this?
8 and 55 are correct, but -57 mod 59 = 2 and not -57. How do I fix this?
The %
operator in Java isn't modulus - it's the remainder operator. 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.
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.
See more on this question at Stackoverflow