Recognizing when to use the modulus operator

前端 未结 19 805
醉梦人生
醉梦人生 2020-11-29 16:40

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 u

相关标签:
19条回答
  • 2020-11-29 16:54

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

    temp = x - (x % 10); //Restrict x to being a multiple of 10
    
    0 讨论(0)
  • 2020-11-29 16:55

    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.

    0 讨论(0)
  • 2020-11-29 16:55

    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;
    
    0 讨论(0)
  • 2020-11-29 16:59

    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.

    0 讨论(0)
  • 2020-11-29 17:02

    Converting linear data structure to matrix structure: where a is index of linear data, and b is number of items per row:

    row = a/b
    column = a mod b
    

    Note above is simplified logic: a must be offset -1 before dividing & the result must be normalized +1.

    Example: (3 rows 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 of modulus: hashing a number by place. Suppose you wanted to store year & month in a six digit number 195810. month = 195810 mod 100 all digits 3rd from right are divisible by 100 so the remainder is the 2 rightmost digits in this case the month is 10. To extract the year 195810 / 100 yields 1958.

    0 讨论(0)
  • 2020-11-29 17:02

    Calculation of prime numbers

    0 讨论(0)
提交回复
热议问题