Are there any normal mathematical quotient and remainder for `int` somewhere in C++?

Viewed 145

Remainder is always positive, for example,

remainder(-1, 7) == 6

not -1

And quotient should be rounded towards minus infinity, not towards zero, for example,

quotient(-1, 7) == -1

not 0.

Are there such functions somewhere in stdlib?

2 Answers

Are there any normal mathematical quotient and remainder for int somewhere in C++?

The % is the remainder operator, but we can use it to nearly get us there.

To achieve the Euclidean modulo

 7 modulo  3 -->  1  
 7 modulo -3 -->  1  
-7 modulo  3 -->  2  
-7 modulo -3 -->  2   

Use

int modulo_Euclidean(int a, int b) {
  int m = a % b;
  if (m < 0) {
    // m += (b < 0) ? -b : b; // avoid this form: it is UB when b == INT_MIN
    m = (b < 0) ? m - b : m + b;
  }
  return m;
}

See also Fastest way to get a positive modulo in C/C++ which covers various pitfalls.

you can do (num1 % num2 + num2) % num2 to get the remainder when you divide num1 by num2 and floor(1.0 * num1 / num2) to get a rounded down quotient. (floor is found in the cmath library)

Related