naomik naomik - 3 months ago 17
Javascript Question

How to simplify modulus arithmetic?

I have

let f = x => x % 4 === 0 ? 0 : 4 - x % 4


But that's a piece of garbage function. Help.

x
is never going to be negative.





Here's a sort of Table of Truth, or something.

x x % 4 4 - (x % 4) f(x)
0 0 4 0
1 1 3 3
2 2 2 2
3 3 1 1
4 0 4 0
5 1 3 3
6 2 2 2
7 3 1 1
8 0 4 0
9 1 3 3


I'm trying to find some correlations here, but it's late and I don't think my brain is working correctly. zzz

What I'm seeing in the
f(x)
column is a sort of reverse modulus, whereby the outputs cycle from 032103210... instead of 01230123...

I'm sensing some use of
Math.max
or
Math.min
in combination with
Math.abs
might help … There's probably an
x * -1
in there somewhere too …

Can you help me write
f
such that it doesn't suck so badly ?

Answer

Something like this will definitely do:

(4 - (x % 4)) % 4

Here's some more truth:

x   x % 4     4 - (x % 4)     (4 - (x % 4)) % 4
0   0         4               0
1   1         3               3
2   2         2               2
3   3         1               1
4   0         4               0
5   1         3               3
6   2         2               2
7   3         1               1
8   0         4               0
9   1         3               3