Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the fastest algorithm to divide an integer by 3 without using a division instruction? [duplicate]

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 781
Greg Dean Avatar asked Nov 25 '22 16:11

Greg Dean


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 87
Martin Dorey Avatar answered Nov 28 '22 05:11

Martin Dorey