I am converting a program written in Python to Java. There is an equation in Python code: (19 - 20) % 91
and it Java version is (19 - 20) % 91
means same. This equation is giving the answer 90 in Python but, in Java it is giving the answer -1. How do I modify this equation from Python to Java so that it can work and run properly?
Asked
Active
Viewed 158 times
0

Manbir Judge
- 113
- 1
- 13
-
5Does this answer your question? [Mod in Java produces negative numbers](https://stackoverflow.com/questions/5385024/mod-in-java-produces-negative-numbers) – Yanirmr Nov 03 '20 at 11:40
-
look that question: https://stackoverflow.com/questions/5385024/mod-in-java-produces-negative-numbers – Yanirmr Nov 03 '20 at 11:40
-
The java code already runs properly, according to the definition of the java language. – NomadMaker Nov 03 '20 at 12:25
1 Answers
1
The problem here is that in Python the % operator returns the modulus and in Java it returns the remainder. These functions give the same values for positive arguments, but the modulus always returns positive results for negative input, whereas the remainder may give negative results. There's some more information about it in this question.
You can find the positive value by doing this:
int i = (19-20) % 91;
if (i<0) i += 91;
Or you can use Math.floorMod():
Math.floorMod((19-20), 91);

Barış Çiçek
- 341
- 2
- 12