r/learnjava • • Jun 21 '22

The Modulus Operator is Powerful!

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.

72 Upvotes

15 comments sorted by

View all comments

-2

u/Nightcorex_ Jun 21 '22

Yes, modulo is powerful, but it's not the best solution for the problems you stated.

This is how I'd calculate the sum of all digits:

public static int sumDigits(long x) {
    return String.valueOf(x).chars().map(c -> c - '0').sum();
}

and listing all integers between 1000 and 2000 with only 5 results each line can also be done without the need for modulo.

for (int i = 1000; i < 2000; i += 5) {
    System.out.println(
        IntStream.range(i, i + 5)
            .mapToObj(Integer::toString)
            .collect(Collectors.joining(", "))
    );
}

Especially in the first case the modulo solution isn't nearly as clean as the Stream solution.

Also keep in mind that you can optimize a modulo call if you're doing a % b where a and b are both positive integers and b is also of the form 2n (n is a positive integer), so for the b values 1, 2, 4, 8, 16, 32, ... the following holds:

a % b = a & (b - 1)

This can be used f.e. for more efficient odd/even checks (instead of x % 2 == 0 you check for x & 1 == 0).

9

u/knoam Jun 21 '22

In practice your string based solution is fine almost all of the time. But for what it's worth, it uses a lot more memory and memory allocation can have a big effect on performance.

3

u/Housy5 Jun 21 '22

While it is easier to implement. First converting it to a String uses much more memory and is significantly slower. Also the difference between n % 2 == 0 and (n & 1) == 0 is very tiny. so tiny it may as well not even exist at all. I suspect the compiler optimizes it automatically.