Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recognizing when to use the modulus operator

I know the modulus (%) operator calculates the remainder of a division. How can I identify a situation where I would need to use the modulus operator?

I know I can use the modulus operator to see whether a number is even or odd and prime or composite, but that's about it. I don't often think in terms of remainders. I'm sure the modulus operator is useful, and I would like to learn to take advantage of it.

I just have problems identifying where the modulus operator is applicable. In various programming situations, it is difficult for me to see a problem and realize "Hey! The remainder of division would work here!".

like image 994
Codebug Avatar asked Apr 09 '10 16:04

Codebug


People also ask

In which situation do you use modulus operator?

The modulus operator returns the remainder of a division of one number by another. In most programming languages, modulo is indicated with a percent sign. For example, "4 mod 2" or "4%2" returns 0, because 2 divides into 4 perfectly, without a remainder.

What is modulus used for in coding?

What is modulus? It's the other part of the answer for integer division. It's the remainder. Remember in grade school you would say, “Eleven divided by four is two remainder three.” In many programming languages, the symbol for the modulus operator is the percent sign (%).

How do you use the modulus operator in math?

The modulo operation (abbreviated “mod”, or “%” in many programming languages) is the remainder when dividing. For example, “5 mod 3 = 2” which means 2 is the remainder when you divide 5 by 3.


2 Answers

Imagine that you have an elapsed time in seconds and you want to convert this to hours, minutes, and seconds:

h = s / 3600; m = (s / 60) % 60; s = s % 60; 
like image 146
Paul R Avatar answered Sep 19 '22 02:09

Paul R


0 % 3 = 0; 1 % 3 = 1; 2 % 3 = 2; 3 % 3 = 0; 

Did you see what it did? At the last step it went back to zero. This could be used in situations like:

  1. To check if N is divisible by M (for example, odd or even) or N is a multiple of M.

  2. To put a cap of a particular value. In this case 3.

  3. To get the last M digits of a number -> N % (10^M).
like image 34
SysAdmin Avatar answered Sep 22 '22 02:09

SysAdmin