#53 – Modulus

The modulus operator %, used as a binary operator

a % b

is defined as the remainder of a (dividend) divided by b (divisor).  Also known as “modulo“.

The idea is to determine the maximum integer that you can multiply b by to get a result <=a. Let’s call this integer n.  Then the remainder is just a – (b * n).

Examples:

 int n1 = 5 % 2;    // 1  [5-(2*2)]
 int n2 = 39 % 5;   // 4  [39-(5*7)]
 int n3 = 10 % 2;   // 0  [10-(2*5)]

If a is equal to b, the remainder is always 0.

If a is less than b, the remainder is always equal to a.

If either a or b is negative, the result always matches the sign of a.

 int n5 = -5 % 2;   // -1
 int n6 = 5 % -2;   //  1
 int n7 = -5 % -2;  // -1

C# also supports the use of the modulus operator for floating point numbers:

 double d1 = 42.5 % 12.2;  // ~5.9 [42.5-(12.2*3)]
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #53 – Modulus

  1. kai zhou says:

    Great summary, thank you Sean.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: