Wednesday, May 27, 2009

Fast division


This is a trick I wish I'd known back in 2000:

Replace:

int exactDiv3(int x) { // given that x is a multiple of 3
return x/3;
}

With:

int exactDiv3(int x) {
return x * 0xaaaaaaab;
}

Wow!

Generate your own optimized magic division numbers!
There is a great blog post detailing how this works here

No comments: