[c#] How can I calculate divide and modulo for integers in C#?

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

This question is related to c# math operators division modulo

The answer is


Before asking questions of this kind, please check 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

There is also Math.DivRem

quotient = Math.DivRem(dividend, divisor, out remainder);

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  

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();

Division is performed using the / operator:

result = a / b;

Modulo division is done using the % operator:

result = a % b;

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to math

How to do perspective fixing? How to pad a string with leading zeros in Python 3 How can I use "e" (Euler's number) and power operation in python 2.7 numpy max vs amax vs maximum Efficiently getting all divisors of a given number Using atan2 to find angle between two vectors How to calculate percentage when old value is ZERO Finding square root without using sqrt function? Exponentiation in Python - should I prefer ** operator instead of math.pow and math.sqrt? How do I get the total number of unique pairs of a set in the database?

Examples related to operators

What is the difference between i = i + 1 and i += 1 in a 'for' loop? Using OR operator in a jquery if statement What is <=> (the 'Spaceship' Operator) in PHP 7? What does question mark and dot operator ?. mean in C# 6.0? Boolean operators ( &&, -a, ||, -o ) in Bash PowerShell and the -contains operator How do I print the percent sign(%) in c Using the && operator in an if statement What do these operators mean (** , ^ , %, //)? How to check if div element is empty

Examples related to division

Division in Python 2.7. and 3.3 Python3 integer division How to do integer division in javascript (Getting division answer in int not float)? How can I do division with variables in a Linux shell? Python: Remove division decimal How to get a float result by dividing two integer values using T-SQL? Divide a number by 3 without using *, /, +, -, % operators Why does integer division in C# return an integer and not a float? How to check if number is divisible by a certain number? C++ Best way to get integer division and remainder

Examples related to modulo

'MOD' is not a recognized built-in function name Modulo operation with negative numbers Can't use modulus on doubles? Assembly Language - How to do Modulo? How to use mod operator in bash? How can I calculate divide and modulo for integers in C#? What is the result of % in Python? How does java do modulus calculations with negative numbers? Integer division with remainder in JavaScript? How to code a modulo (%) operator in C/C++/Obj-C that handles negative numbers