3 ms·
I would consider the mod operator to be pretty basic though. (Feel free to call me out if I'm just being naive.) Outside of the mod operator, you could always
by pyre 16y ago
I would consider the mod operator to be pretty basic though. (Feel free to call me out if I'm just being naive.)
Outside of the mod operator, you could always use a combo of floor() and ceiling() (which I assume most languages have in a standard library). e.g.:
from math import floor,ceil
def divisible_by_3(n):
result = n / 3.0
return ceil(result) == floor(result)
Or even more basic:
def divisible_by_3(n):
result = n / 3.0
return int(result) == result
- chipsy 16y agoThe main danger with using the mod operator is that you can get an off-by-one if you aren't in the habit of using it and forget the exact definition. If that's in doubt, rolling your own thing with a division or a while/if makes for a stronger guarantee of success on the first try. In an interview you could explain your reasoning for such a detour as well, which might work out better than just "knowing the answer."
- robinduckett 16y agoI used the old int(i) == i (or even, int(i/2) == i/2) way before I knew about the mod operator.