Modulus Calculation with Negative Numbers in Java
In Java, the modulus operator (%) returns the remainder after dividing two numbers. However, when dealing with negative numbers, the result may not be as expected.
Issue:
A developer encounters an unexpected result when performing modulus calculations with negative numbers, specifically -13 % 64. Instead of the desired outcome of 51, the result is -13.
Explanation:
The definition of modulus for negative numbers varies across programming languages. In Java, the remainder returned by the modulus operator has the same sign as the dividend (numerator). Therefore, -13 % 64 evaluates to -13.
Solution:
To obtain the desired result of 51, the following correction can be applied:
<code class="java">int r = x % n; if (r > 0 && x < 0) { r -= n; }</code>
This code ensures that the remainder is positive when the dividend is negative.
Alternatively, if the language returns a negative remainder for negative inputs and the developer prefers a positive result, the following adjustment can be made:
<code class="java">int r = x % n; if (r < 0) { r += n; }</code>
This code converts the negative remainder to a positive value.
The above is the detailed content of Here are a few title options, playing with the question format: * **Why is -13 % 64 not 51 in Java?** (Simple and direct) * **Java Modulus Operator and Negative Numbers: How to Get the Expected Resu. For more information, please follow other related articles on the PHP Chinese website!