SoFunction
Updated on 2025-03-08

Implementation methods of dividing (/) and taking balance (%) in Java

The two concepts of modulus operation and balance operation overlap but are not completely consistent. The main difference is that the operations are different when performing division operations on negative integers.

For the shaping numbers a and b, the methods of modulus calculation or remnant calculation are:

1. Find the integer quotient c = a / b;

2. Calculate the modulus or remainder r = a - c* b.

The modulus operation and the balance operation are different in the first step:

When taking the c value, the remainder is rounded in the direction 0; when taking the c value, the modulus is rounded in the direction of negative infinite

The meaning of operator % in each environment is different, C/C++, Java is the balance, and python is the modular

The Java remnant operation rules are as follows:

a%b = a - (a/b)*b

Let's look at a piece of code first:

public class Division_remainder {
  public static void main(String[] args) {
    int a = 13 / 5;
    int b = 13 % 5;
    int c = 5 / 13;
    int d = 5 % 13;
    int e = 13 / -5;
    int f = -13 / 5;
    int h = -13 % 5;
    int j = 13 % -5;
    (a + "," + b);
    (c + "," + d);
    (e + "," + f);
    (h + "," + j);
  }

The result is:

2,3
0,5
-2,-2
-3,3

Let’s analyze it one by one:

a = 13 / 5, a = 2, which is actually 13 / 5 in mathematics, and the result is 2.

b = 13 % 5, b = 3, which is also a mathematical operation, resulting in the remainder being 3.

c = 5 / 13, c = 0, because the divisor is smaller than the divisor, the result can be regarded as, but the int type is an integer type, so the result is only 0.

d = 5 % 13, d = 5, mathematically stipulates: if the dividend is smaller than the dividend, the quotient is 0, and the remainder is the dividend itself.

Needless to say, e and f both have -2 results.

But how do h and j be one -3 and one 3, because the symbol of the remnant operation is determined based on the first operation number, the result of -13 % 5 is -3, and the result of 13 % -5 is 3.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.