1

In C#, one can easily get the quotient and modulus of an integer division:

var quotient = 7 / 3;
var modulus = 7 % 3;

However, as far as I can tell it doesn't have a divmod function, allowing you to get both at once. Is there a way to do this? Getting them separately would seem to require the divison to be done twice, unnecessarily, as the processor surely provides both values at the same time for one division.

Jez
  • 27,951
  • 32
  • 136
  • 233
  • In C++, a good compiler would detect that and do the right thing. Don't know about C# – Thomas Weller Dec 22 '22 at 19:12
  • @ThomasWeller [apparently not](https://sharplab.io/#v2:EYLgxg9gTgpgtADwGwBYA0AXEBDAzgWwB8ABAJgEYBYAKGIGYACMhgYQYG8aHunGBLAHYYGAWWwCArtgA2AET4A3AEox8ACkHCEaBpoYBPHRAnC9UAJQcuPG1AYBeBggYBSAwG5rN7sQDsThgB6Dy8GAF9Q0PpdIQYAIQk+aQxBeWVVDVjtGOFDBmNTWIsram8eP1FsDAALADo0lXVsvIKGC09SngjqMKA==) (another Fun Fact is that apparently `Math.DivRem` does not use remainder output of `idiv`, it takes the quotient and then manually computes the remainder with an extra `imul` and `sub`) – harold Dec 22 '22 at 19:15
  • @harold: so that'll be one reason why C++ is still around and people stick to it. – Thomas Weller Dec 22 '22 at 19:18

1 Answers1

5

You can use Math.DivRem to get both the quotient and the remainder.

var quotient = Math.DivRem(dividend, divisor, out var remainder);
Batesias
  • 1,914
  • 1
  • 12
  • 22