100

How can I calculate division and modulo for integer numbers in C#?

2
  • 18
    This might be too basic, but it is a real question...
    – Aryabhatta
    Mar 21, 2011 at 20:26
  • 3
    A related post and a must read blog on why % operator is not the modulus operator in C#.
    – RBT
    Jul 29, 2017 at 11:03

5 Answers 5

141

Here's an answer from the MSDN documentation.

When you divide two integers, the result is always an integer. For example, the result of 7 / 3 is 2. To determine the remainder of 7 / 3, use the remainder operator (%).

int a = 5;
int b = 3;

int div = a / b; //quotient is 1
int mod = a % b; //remainder is 2
10
  • 12
    % returns the remainder, not the modulus (as you point out). They arent the same thing, and can cause problems when dealing with unusual cases (e.g. negative indexes). However, it can be used like the modulus operator when just looking for, e.g., every 10th iteration of a weakly positive indexer. Perhaps you could explain how to calculate the real modulus?
    – Cor_Blimey
    Sep 12, 2012 at 23:14
  • 1
    True, I read posts like this, and I had problems in my application :)
    – apocalypse
    Apr 1, 2013 at 14:39
  • 1
    ...What exactly is the point of declaring a and b if you aren't going to use them? :D Apr 27, 2013 at 16:54
  • 1
    Perhaps the user was searching (like me) for a DivRem function, so the question could be not as trivial as it seems at first glance. Thanks @danodonovan
    – Tancredi
    Oct 29, 2018 at 19:46
  • 1
    The answer is not as simple as this answer claims, as others have also pointed out, and can lead to hard-to-debug mistakes. See https://stackoverflow.com/questions/10065080/mod-explanation
    – SansWit
    Jun 22, 2019 at 17:58
101

There is also Math.DivRem

quotient = Math.DivRem(dividend, divisor, out remainder);
5
  • 3
    This should be the correct answer in my opinion, because it provides the quotient AND the remainder in one function. I am not sure which approach performs better (using "a / b" to get quotient and then "a % b" to get the remainder or Math.DivRem), but this approach certainly is much nicer to read (in my case I need to know both quotient and remainder) - thank you!
    – Igor
    Aug 6, 2015 at 6:47
  • 2
    @Igor thanks, when the original question was answered this function didn't exist! However, the function's existence does make as-cii's remark about checking the documentation look a bit silly.... :) Aug 6, 2015 at 9:30
  • 10
    Just to avoid confusion, Math.DivRem does not compute div and mod in one operation. It is just a helper function and its source code is exactly: public static int DivRem(int a, int b, out int result) { result = a%b; return a/b; }.
    – NightElfik
    Jan 6, 2016 at 5:51
  • 11
    @NightElfik The implementation could change in the future, and it is easier for the runtime to identify a method call for optimization than disjoint div and rem instructions
    – kbolino
    Jan 21, 2016 at 2:46
  • 9
    @kbolino That's a great prediction, since it has changed, at least in .NET Core, to divide & subtract. And there's further optimisations planned in RyuJIT to use a single x86 div instruction, though admittedly the JIT changes should also detect the % and / operators if used individually.
    – Bob
    Jan 23, 2017 at 11:35
17

Fun fact!

The 'modulus' operation is defined as:

a % n ==> a - (a/n) * n

Ref:Modular Arithmetic

So you could roll your own, although it will be FAR slower than the built in % operator:

public static int Mod(int a, int n)
{
    return a - (int)((double)a / n) * n;
}

Edit: wow, misspoke rather badly here originally, thanks @joren for catching me

Now here I'm relying on the fact that division + cast-to-int in C# is equivalent to Math.Floor (i.e., it drops the fraction), but a "true" implementation would instead be something like:

public static int Mod(int a, int n)
{
    return a - (int)Math.Floor((double)a / n) * n;
}

In fact, you can see the differences between % and "true modulus" with the following:

var modTest =
    from a in Enumerable.Range(-3, 6)
    from b in Enumerable.Range(-3, 6)
    where b != 0
    let op = (a % b)
    let mod = Mod(a,b)
    let areSame = op == mod
    select new 
    { 
        A = a,
        B = b,
        Operator = op, 
        Mod = mod, 
        Same = areSame
    };
Console.WriteLine("A      B     A%B   Mod(A,B)   Equal?");
Console.WriteLine("-----------------------------------");
foreach (var result in modTest)
{
    Console.WriteLine(
        "{0,-3} | {1,-3} | {2,-5} | {3,-10} | {4,-6}", 
        result.A,
        result.B,
        result.Operator, 
        result.Mod, 
        result.Same);
}

Results:

A      B     A%B   Mod(A,B)   Equal?
-----------------------------------
-3  | -3  | 0     | 0          | True  
-3  | -2  | -1    | -1         | True  
-3  | -1  | 0     | 0          | True  
-3  | 1   | 0     | 0          | True  
-3  | 2   | -1    | 1          | False 
-2  | -3  | -2    | -2         | True  
-2  | -2  | 0     | 0          | True  
-2  | -1  | 0     | 0          | True  
-2  | 1   | 0     | 0          | True  
-2  | 2   | 0     | 0          | True  
-1  | -3  | -1    | -1         | True  
-1  | -2  | -1    | -1         | True  
-1  | -1  | 0     | 0          | True  
-1  | 1   | 0     | 0          | True  
-1  | 2   | -1    | 1          | False 
0   | -3  | 0     | 0          | True  
0   | -2  | 0     | 0          | True  
0   | -1  | 0     | 0          | True  
0   | 1   | 0     | 0          | True  
0   | 2   | 0     | 0          | True  
1   | -3  | 1     | -2         | False 
1   | -2  | 1     | -1         | False 
1   | -1  | 0     | 0          | True  
1   | 1   | 0     | 0          | True  
1   | 2   | 1     | 1          | True  
2   | -3  | 2     | -1         | False 
2   | -2  | 0     | 0          | True  
2   | -1  | 0     | 0          | True  
2   | 1   | 0     | 0          | True  
2   | 2   | 0     | 0          | True  
7
  • "Now here I'm relying on the fact that integer division in C# is equivalent to Math.Floor (i.e., it drops the fraction)" - But it's not. Integer divison rounds towards zero, Math.Floor rounds towards negative infinity.
    – Joren
    Mar 19, 2013 at 14:09
  • @Joren Sorry, but no - try running this: Enumerable.Range(0, 10).Select(x => (double)x / 10.0).Select(x => (int)x).ToList().ForEach(x => Console.WriteLine(x)); - all 0's
    – JerKimball
    Mar 19, 2013 at 14:26
  • 2
    First, I'm talking about integer division. What happens if you do a floating-point division and then cast to integer is irrelevant (even though it gives the same result). Second, I'm not sure why you would expect integers between 0 and 9 to give anything other than 0 after dividing by 10 and truncating to the integer part. If that resulted in 1 that would be rounding away from zero or towards positive infinity. Third, there is no difference whatsoever between rounding towards zero and rounding towards negative infinity for positive numbers, so you're not even addressing the issue.
    – Joren
    Mar 19, 2013 at 16:02
  • Math.Floor(-10.0 / 3.0) and -10 / 3 are not the same thing.
    – Joren
    Mar 19, 2013 at 16:07
  • @joren ah, I see the disconnect here - no, I'm not performing integer division, I'm performing double division, then casting the result to integer - very different.
    – JerKimball
    Mar 19, 2013 at 16:12
15

Division is performed using the / operator:

result = a / b;

Modulo division is done using the % operator:

result = a % b;
3
  • 1
    +1: Conveniently leaving out the type makes it a better answer :-) I believe this works with System.Numeric.BigInteger in 4.0 too.
    – Aryabhatta
    Mar 21, 2011 at 20:15
  • 5
    % --> as Cor_Blimey said, it returns remainder not the modulus. For example: (-5 % 3) == -2 [C#], -5 mod 3 = 1 [wolframalpha.com].
    – apocalypse
    Apr 1, 2013 at 14:35
  • 2
    Note: Modulo is not the same as Modulus. Modulo is the remainder, Modulus is the absolute value.
    – Ryan
    May 20, 2016 at 4:30
-5

Read two integers from the user. Then compute/display the remainder and quotient,

// When the larger integer is divided by the smaller integer
Console.WriteLine("Enter integer 1 please :");
double a5 = double.Parse(Console.ReadLine());
Console.WriteLine("Enter integer 2 please :");
double b5 = double.Parse(Console.ReadLine());

double div = a5 / b5;
Console.WriteLine(div);

double mod = a5 % b5;
Console.WriteLine(mod);

Console.ReadLine();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.