What’s the fastest way to divide an integer by 3?

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.

Leave a Comment