DEV Community

Discussion on: % Is Not Modulo

Collapse
 
itr13 profile image
Mikael Klages • Edited

I've learnt to always check that when dealing with potential negative numbers in new languages, and sometimes in ones 8 know already, too just to be safe. Though I must admit I sometimes take the lazy route of (a%n+n)%n since it's faster to write.

Collapse
 
nichartley profile image
Nic Hartley

As neat as that one-liner is, I'm not a huge fan of it. The "correct" function is only a few lines in any language, and makes it explicitly clear what you're trying to do.

...that said, I have used it more than a few times when I just need something working correctly, and I'd be surprised if the compiler couldn't optimize it into something better.