4

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?

Dims
  • 47,675
  • 117
  • 331
  • 600
  • You can massage the remainder with `rem = (rem + divisor) % divisor` to make it be positive. Not sure there's a similarly concise adjustment for quotient. – Nathan Pierson Mar 30 '21 at 21:10
  • 1
    Related: [Fastest way to get a positive modulo in C/C++](https://stackoverflow.com/questions/14997165/fastest-way-to-get-a-positive-modulo-in-c-c) – Brian61354270 Mar 30 '21 at 21:12
  • You can use the `div` function https://www.tutorialspoint.com/c_standard_library/c_function_div.htm and make the adjustments on your own. – mch Mar 30 '21 at 21:12
  • @Nathan Pierson `rem = (rem + divisor) % divisor` risks overflow with `rem + divisor`. – chux - Reinstate Monica Mar 30 '21 at 21:28

2 Answers2

3

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.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
  • Might be worth linking the question where you [previously posted this as an answer](https://stackoverflow.com/a/57544473/11082165) for its discussion about UB risks. – Brian61354270 Mar 30 '21 at 21:23
1

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)

TruVortex_07
  • 280
  • 1
  • 3
  • 16