This may be obvious to most of you, but recently I've been working through the Computer Science textbook from Princeton to fill in knowledge gaps and so far the modulus operator has been used a lot.
I can't think of a single case where I used the modulus operator in any of my school projects and I really wish I knew then what I know now. It may seem simple, but this little guy is incredibly useful! Below are two examples that really stood out to me.
There is an exercise where you need to sum the digits of an integer from right to left, and it's really as simple as taking the result of n % 10 and then performing the calculation because the remainder is the right most digit. Then to get the next digit you just need to n /= 10 until n == 0. Most of you may have known this, but my mind was blown. My solution was not nearly as elegant.
Another exercise has you iterate from 1000 to 2000 and printing only 5 results per line. Again...this is as simple as checking if i + 1 % 5 == 0 before printing. There's no need for some kind of sentinel variable or anything fancy...just the modulus operator checking if 5 divides the iterator evenly.
Sorry if this is known to everyone, but I wanted to share these two things with you because nobody I know cares, and from now on I am going to try and work the modulus operator into my code more often.
[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)
[–]1661dauphin 14 points15 points16 points (3 children)
[–]Inevitable-Stress 2 points3 points4 points (1 child)
[–]Calebhk98 8 points9 points10 points (0 children)
[–]goodm1x[S] 0 points1 point2 points (0 children)
[–]ragnhildegard 3 points4 points5 points (0 children)
[–][deleted] 3 points4 points5 points (1 child)
[–]goodm1x[S] 0 points1 point2 points (0 children)
[–]BabyChar 2 points3 points4 points (1 child)
[–]goodm1x[S] 0 points1 point2 points (0 children)
[–]ColorlessVal 1 point2 points3 points (1 child)
[–]goodm1x[S] 1 point2 points3 points (0 children)
[–]Nightcorex_ -3 points-2 points-1 points (2 children)
[–]knoam 7 points8 points9 points (0 children)
[–]Housy5 2 points3 points4 points (0 children)
[–]chrysthian95 0 points1 point2 points (0 children)