In java, the difference between modulus and remainder

The difference between modulo and remainder

  For integers a and b, the modulus operation or remainder operation method is:

  1. Find the integer quotient: c = a/b;
  2. Calculate the modulus or remainder: r = a-c * b

  Modulus operation and remainder operation are different in the first step: When the remainder operation takes the value of c, it rounds to 0 (fix() function); while the modulus operation calculates the value of c, it goes to negative infinity. Rounding (floor() function).

  For example, calculation: -7 Mod 4
  then: a = -7; b = 4; the
  first step: find the integer quotient c, such as the modulo operation c = -2 (round to negative infinity), find the remainder c =- 1 (rounded towards 0);

  Step 2: The formula for calculating modulus and remainder is the same, but because of the different value of c, r = 1 when calculating the modulus and r = -3 when calculating the remainder.

Induction:
  When the signs of a and b are the same, the value of c obtained by the modulus operation and the remainder operation are the same, so the results are the same.
  When the symbols are inconsistent, the result is different. The sign of the modulo operation result is the same as b, and the sign of the remainder operation result is the same as a.

  In addition, the meaning of the% operator is different in each environment, such as c/c++, java is the remainder, and python is the modulus.

Java program example:

public class Main{
    
    
	public static void main(String[] args){
    
    
		System.out.println("-3,2取模="+Math.floorMod(-3,2));
        System.out.println("-3,2取余="+ -3%2);
        System.out.println("3,-2取模="+Math.floorMod(3,-2));
        System.out.println("3,2取余="+ 3%-2);
	}
}

result:

-3,2取模=1
-3,2取余=-1
3,-2取模=-1
3,2取余=1

Guess you like

Origin blog.csdn.net/qq_43692768/article/details/109696417
Recommended