Difference between "Math.DivRem" and % operator?

mbrownnyc picture mbrownnyc · Aug 8, 2011 · Viewed 14.2k times · Source

What is the difference between System.Math.DivRem() and the % operator?

Answer

BoltClock picture BoltClock · Aug 8, 2011

% gives you the remainder of a division and discards the quotient altogether, while DivRem() calculates and returns both the quotient and the remainder.

If you're only concerned about the remainder of a division between two integers, use %:

int remainder = 10 % 3;
Console.WriteLine(remainder); // 1

If you need to know how many times 10 was divided by 3 before having a remainder of 1, use DivRem(), which returns the quotient and stores the remainder in an out parameter:

int quotient, remainder;
quotient = Math.DivRem(10, 3, out remainder);
Console.WriteLine(quotient);  // 3
Console.WriteLine(remainder); // 1