5 ms·
Generally, binary math becomes easier to understand if you play with a decimal analogue. Let's say that our integer domain is 0 to 9999 (decimal) but you have
by pw0ncakes 17y ago
Generally, binary math becomes easier to understand if you play with a decimal analogue.
Let's say that our integer domain is 0 to 9999 (decimal) but you have enough space to handle up to 9 digits. To integer-divide something by 3, you can multiply by 33334 and shift-right 5 digits (i.e. drop the last 5):
7939 * 33334 = 264638626;
2646 (right answer) after dropping 5 digits.
Note that 33334/100000 is close enough to 1/3 that, given our finite domain (as with [0..9999], or [0..2^31-1]), the error is too small to matter.
For some divisors, we're better off. For example, if n = 25 and we're in base 10, you can multiply by 4 and drop 2 digits, as 4/100 = 1/25.
Same principle applies to binary.