Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

int x = n / 3;  // <-- make this faster  // for instance  int a = n * 3; // <-- normal integer multiplication  int b = (n << 1) + n; // <-- potentially faster multiplication 
like image 765
Greg Dean Avatar asked Oct 05 '08 01:10

Greg Dean


People also ask

How do you divide 3 by binary?

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.


1 Answers

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.

like image 152
Martin Dorey Avatar answered Sep 17 '22 16:09

Martin Dorey