Recognizing when to use the module operator

I know that the module operator (%) calculates the remainder of the division. How can I determine a situation where I will need to use the module operator?

I know that I can use the module operator to see even or odd numbers or prime or compound, but that's about it. I do not often think in terms of leftovers. I am sure that the module operator is useful, and I would like to learn how to use it.

I just have problems determining where the module operator is applicable. In various programming situations, it’s hard for me to understand the problem and understand: β€œHey, the rest of the unit will work here!”

+44
operators modulo
Apr 09 '10 at 16:54
source share
17 answers

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

h = s / 3600; m = (s / 60) % 60; s = s % 60; 
+23
Apr 09 '10 at 16:57
source share
 0 % 3 = 0; 1 % 3 = 1; 2 % 3 = 2; 3 % 3 = 0; 

Did you see what he did? In the last step, he returned to zero. This can be used in situations such as:

  • To check if N is divisible by M (e.g. odd or even) or N is a multiple of M.

  • To put a cap of a certain value. In this case 3.

  • To get the last M digits of a number β†’ N% (10 ^ M).
+18
Apr 09 '10 at 17:08
source share

I use it for progress indicators and the like that mark progress through a long cycle. Progress is reported only every n-th time through the cycle or when count% n == 0.

+16
Apr 09 '10 at 17:18
source share

I used it when limiting the number to multiple multiples:

 temp = x - (x % 10); //Restrict x to being a multiple of 10 
+10
Apr 09 '10 at 16:59
source share
  • Packing values ​​(e.g. hours).
  • Providing finite fields with symmetric key algorithms.
  • Bitwise operations.

And so on.

+10
Apr 09 '10 at 17:08
source share

Example. You have a message of X bytes, but in your protocol the maximum size is Y and Y <X. Try writing a small application that breaks the message into packets, and you will come across a mod :)

+4
Apr 09 '10 at 16:57
source share

Converting a linear data structure to a matrix structure: where a is the index of linear data, and b is the number of elements in the row:

 row = a/b column = a mod b 

The note above is a simplified logic: a must be offset -1 before division, and the result should be normalized +1.

Example: (3 lines of 4)

 1 2 3 4 5 6 7 8 9 10 11 12 (7 - 1)/4 + 1 = 2 7 is in row 2 (7 - 1) mod 4 + 1 = 3 7 is in column 3 

Another common use for a module is to hash a number locally. Suppose you want to store the year and month in the six-digit number 195810. month = 195810 mod 100 all the digits from the third one are rightfully divided by 100, so the remainder is the two most right digits, in this case the month is 10. To extract the year 195810 / 100 gives 1958

+4
May 25 '16 at 23:43
source share

Prime Calculation

+3
Apr 09 '10 at 16:57
source share

At any time, when you have a separation and you want to express a remainder other than decimal, the mod operator is suitable. Things that come to mind are usually when you want to do something human-readable with the remainder. List how many items you can put in buckets and say "5 left." Good.

In addition, if you have ever been in a situation where you can type rounding errors, modular division is good. For example, if you divide by 3 quite often, you do not want to pass by .33333 as the remainder. Transfer of remainder and divider (i.e. Fractions) is appropriate.

+3
Apr 09 '10 at
source share

As @jweyrich says, wrapping values. I found the mod very convenient when I have a finite list, and I want to iterate over it in a loop - as a fixed list of colors for some user interface elements, for example, for diagrams where I want all series to be as different as possible but when I ran out of colors, just to start at the beginning. It can also be used with, say, patterns, so the second time a red one appears, it crashes; third time, dotted, etc. - but the mod is just used to get red, green, blue, red, green, blue, forever.

+3
Apr 09 '10 at 17:37
source share

The module can be useful for converting and dividing total minutes into "hours and minutes":

hours = minutes / 60

minutes_left = minutes% 60

At the beat of the clock, we need to break the decimal part, and it will depend on the language you use.

Then we can change the output accordingly.

+3
Aug 02
source share

There are many examples when this is helpful.

If you need to limit a number within a certain range, you can use mod. For example, to create a random number from 0 to 99, you can say:

 num = MyRandFunction() % 100; 
+2
Apr 09 '10 at 16:57
source share

The module is also very useful if for some crazy reason you need to do integer division and get a decimal number, and you cannot convert an integer to a number that supports decimal division, or if you need to return a part instead of a decimal fraction.

I will use % as a module operator

for example

2/4 = 0

where is it done

2/4 = 0 and 2 % 4 = 2

So, you can be really crazy and say that you want to allow the user to enter a numerator and a divisor, and then show the result as an integer, and then a fractional number.

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

Another case where modulo separation is useful is to increase or decrease the number, and you want to shift the number to a certain range of numbers, but when you get to the top or bottom, you don’t just want to stop, you want the loop up or down at the top of the list, respectively.

Imagine a function in which you iterate over an array.

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

The reason this is n = (n + variable)% (listString.maxIndex + 1) should consider the max account.

These are just some of the things that I had to use for modulation in my programming, not only for desktop applications, but also in the environment of robotics and modeling.

+2
Apr 09 '10 at 17:13
source share
  • Calculation of the greatest common factor
  • Determining whether a number is a palindrome
  • Determining if a number contains only ...
  • Determining the quantity ... the number consists of ...
+2
Apr 09 '10 at 17:49
source share

One use case I've seen recently is when you need to change a number. Thus, 123456 becomes 654321 , for example.

 int number = 123456; int reversed = 0; while ( number > 0 ) { # The modulus here retrieves the last digit in the specified number # In the first iteration of this loop it going to be 6, then 5, ... # We are multiplying reversed by 10 first, to move the number one decimal place to the left. # For example, if we are at the second iteration of this loop, # reversed gonna be 6, so 6 * 10 + 12345 % 10 => 60 + 5 reversed = reversed * 10 + number % 10; number = number / 10; } 
+2
Feb 14 '17 at 19:46
source share

My favorite use is for iteration.

Say that you have a counter that you increment and then want to grab the corresponding elements from the known list, but you only have n tags and you want to repeat the loop.

var indexFromB = (counter-1)%n+1;

Results ( counter=indexFromB ) are given n=3 :

 `1=1` `2=2` `3=3` `4=1` `5=2` `6=3` ... 
+1
Oct 17 '16 at 16:49
source share

This is an easy way to find out even or odd numbers. Just # mod 2, if it is 0, it is odd.

+1
Apr 18 '17 at 15:53 ​​on
source share



All Articles