int x = n / 3; // <-- make this faster // for instance int a = n * 3; // <-- normal integer multiplication int b = (n << 1) + n; // <-- potentially faster multiplication
For example, to divide by 3, we can multiply by 1/3 (0.010101… 2). Note that this particular value is a repeating fraction in both decimal (0.3333…) and binary.
The guy who said "leave it to the compiler" was right, but I don't have the "reputation" to mod him up or comment. I asked gcc to compile int test(int a) { return a / 3; } for an ix86 and then disassembled the output. Just for academic interest, what it's doing is roughly multiplying by 0x55555556 and then taking the top 32 bits of the 64 bit result of that. You can demonstrate this to yourself with eg:
$ ruby -e 'puts(60000 * 0x55555556 >> 32)' 20000 $ ruby -e 'puts(72 * 0x55555556 >> 32)' 24 $
The wikipedia page on Montgomery division is hard to read but fortunately the compiler guys have done it so you don't have to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With