What are some uses of the modulus operator? I know that it calculates the remainder in division so really I am asking what uses does the remainder have?
So far I have used it to check if a number was even and alternate colors on a table.
What are some uses of the modulus operator? I know that it calculates the remainder in division so really I am asking what uses does the remainder have?
So far I have used it to check if a number was even and alternate colors on a table.
13425 m
is 13425 / 1000 km and 13425 % 1000 m
= 13 km and 425 m
rand() % (HIGH - LOW) + LOW
to generate a random number between HIGH and LOWfor(int i=0;i<10;i++)
{
if((i % 2) == 0 )
{
// I'm in an even row
}else{
// I'm in an odd row
}
}
The most basic use
Note: lang used Java
A programming 101 exapmle would be to modulate row colors for data:
for(int i = 0; i < 100; i++)
{
write-color i % 2;
}
Determine if a number is evan or odd:
return number % 2;
Getting an indication of progress in a long running loop by printing a message once every so many iterations.
List<Thing> bigList = readBigList();
for (int i = 0; i < bigList.size(); i++) {
processThing(bigList.get(i));
if (i % 10000 == 0) {
LOG.info("Processed " + i + " out of " + bigList.size() + " items");
}
}
The modulus operator is the single-most important operator in Clock Arithmetic.
It's generally used to check if one number is evenly divisible by another.
if(number % 2 == 0){
// the number is even
} else {
// the number is odd
}
or
if(number % 3 == 0){
// the number is evenly divisible by three
} else {
// the number is not evenly divisible by three
}
If the result of a mod operation is 0, the dividend (number) is evenly divisible by the divisor.
You can take advantage of this to do things like "piano-keys" style alternate-row shading on table data, or printing new column headings every X number of rows, or what have you.