views:

341

answers:

13

I have a quick question about the mod operator. I know what it does; it calculates the remainder of a division. My question is, how can I identify a situation where I would need to use the mod operator? I know I can use the mod 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 mod operator is useful and I would like to learn to take advantage of it. I just have problems identifying where the mod 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!" Any tips or strategies?

Thanks

+1  A: 

Example. You have message of X bytes, but in your protocol maximum size is Y and Y < X. Try to write small app that splits message into packets and you will run into mod :)

Andrey
A: 

There are many instances where it is useful.

If you need to restrict a number to be within a certain range you can use mod. For example, to generate a random number between 0 and 99 you might say:

num = MyRandFunction() % 100;
Justin Ethier
-1. This will generate non-uniform results unless 100 is a divisor of the range of `MyRandFunction()`. (Imagine you want a random numbers in `0 .. RAND_MAX*2/3`.)
KennyTM
@KennyTM: +1. What would probably be better is to be able to pass the 100 _into_ MyRandFunction() which would take care of it properly. Plus that provides better encapsulation, and much looser coupling.
Cam
+2  A: 

Calculation of prime numbers

Mr Roys
Although I haven't really found a situation where I actually needed to calculate them.
Mr Roys
Diffie-Hellman Key Exchange Algorithm, pgp encryption
Hasan Khan
+7  A: 

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;
Paul R
+2  A: 

I've used it when restricting a number to a certain multiple:

temp = x - (x % 10); //Restrict x to being a multiple of 10
Bob
+2  A: 
0 % 3 = 0;
1 % 3 = 1;
2 % 3 = 2;
3 % 3 = 0;

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 (eg: odd 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)
SysAdmin
+3  A: 
  • Wrapping values (like a clock).
  • Provide finite fields to symmetric key algorithms.
  • Bitwise operations.

And so on.

jweyrich
+1  A: 

Any time you have division and want to express the remainder other than in decimal, the mod operator is appropriate. Things that come to mind are generally when you want to do something human-readable with the remainder. Listing how many items you could put into buckets and saying "5 left over" is good.

Also, if you're ever in a situation where you may be accruing rounding errors, modulo division is good. If you're dividing by 3 quite often, for example, you don't want to be passing .33333 around as the remainder. Passing the remainder and divisor (i.e. the fraction) is appropriate.

Matt
+1  A: 

Mod is also very useful if for some crazy reason you need to do integer division and get a decimal out, and you can't convert the integer into a number that supports decimal division, or if you need to return a fraction instead of a decimal.

I'll be using % as the modulus operator

For example

2/4 = 0

where doing this

2/4 = 0 and 2 % 4 = 2

SO you can be really crazy and lets say that you want to allow the user to input a numerator and a divisor, and then show them the result as a whole number, and then a fractional number.

whole Number = numerator/divisor fractionNumerator = numerator % divisor fractionDenominator = divisor

Another Case where modulus division is useful is if you are increasing or decreasing a number and you want to contain the number to a certain range of number, but when you get to the top or bottom you don't want to just stop you want to loop up to the bottom or top of the list respectively.

Imagine a function where you are looping through an array.

Function increase Or Decrease(variable As Integer) As Void
    n = (n + variable) % (listString.maxIndex + 1)  
    Print listString[n]
End Function

The reason that it is n = (n + variable) % (listString.maxIndex + 1) is to allow for the max index to be accounted.

Those are just a few of the things that I have had to use modulus for in my programming of not just desktop applications, but in robotics and simulation environments.

msarchet
+5  A: 

I use it for progress bars and the like that mark progress through a big loop. The progress is only reported every nth time through the loop, or when count%n == 0.

SeaDrive
You too, then? It really makes a big speed difference.
Kawa
A: 

As @jweyrich says, wrapping values. I've found mod very handy when I have a finite list and I want to iterate over it in a loop - like a fixed list of colors for some UI elements, like chart series, where I want all the series to be different, to the extent possible, but when I've run out of colors, just to start over at the beginning. This can also be used with, say, patterns, so that the second time red comes around, it's dashed; the third time, dotted, etc. - but mod is just used to get red, green, blue, red, green, blue, forever.

Carl Manaster
A: 
  • Computing the greatest common divisor
  • Determining if a number is a palindrom
  • Determining if a number consists of only ...
  • Determining how many ... a number consists of...
Helper Method
A: 

So would you guys say that with time, practice, and experience that it gets easier to see situations where the mod operator would be appropriate? The reason I ask is because I've only been programming for around 6 months and still consider myself a beginner.

Will
To quote the faq (http://stackoverflow.com/faq): This is not a discussion board. If you have a response to a question, please post a comment on that answer, not a separate answer.
Bevan