Is there other uses for modulus? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Is there other uses for modulus?

I know the purpose about the operator modulus, gives you the remainder. But I want to know how can I use it if it's not for mathematical problems, for example how to use modulus in gaming programming or something like that.

13th Nov 2016, 9:08 PM
edu
edu - avatar
4 Answers
+ 4
Eureka! I just found a wonderful use for it. Great question, by the way. There are two standard uses: 1. Creating random numbers in programming. So, C++ pulls a random number (that can be very large). If I wanted to get a dice roll from one to six, I would... rand() % 6 + 1; And it would result in numbers from zero to five, plus one. 2. Animation. If you have an animation that is eight frames long, tou could do something like this... total_frames = 8; current_frame++; frame = current_frame % total_frames; So, it has a running frame total that goes well over eight, but mod will keep it under eight.
14th Nov 2016, 12:20 AM
Keto Z
Keto Z - avatar
+ 3
if you want repeat a group of actions you can use it in a loop. for example: for (x = 0; x < 20; x++) { y = x % 5; //six different actions now. switch (y) { case 0: myFunction(); etc. } }
13th Nov 2016, 10:41 PM
Sjoerd Flameling
Sjoerd Flameling - avatar
+ 1
Here are some other examples: You want to determine if a number is even or odd. n % 2 will be 0 if it's even (can be evenly divided by 2) and 1 if it's odd. if (n % 2 == 0) {System.out.println("even");} You want to calculate Chinese zodiac sign for a particular year. The zodiac symbols repeat every 12 years. Input a year, calculate modulo 12, and the output will be a number between 0 and 11. That number will coincide with a particular animal of the Chinese zodiac. 1960 was the year of the rat. 1960 modulo 12 is 4. Input any other year of the rat, and I guarantee you that that year modulo 12 will be 4 also. The other years of the rat were 2008, 1996, 1984, 1972....so if (year % 12 == 4) { System.out.println("It's the year of the rat."); } Then of course, there are many applications with time. Let's say you want to perform an operation 2 times a minute, you could get the seconds from the clock, and if seconds % 30 is equal to 0, it would be time to perform that operation.
2nd Jan 2017, 6:31 AM
Chris Winikka
Chris Winikka - avatar
0
But this is all the same using . Even if you shall programmming games etc.. the basic shall be a mathematic computing...So modulus can be used to ger remainder too
13th Nov 2016, 11:44 PM
Petr Hatina
Petr Hatina - avatar