int x = n / 3; // <-- make this faster
// for instance
int a = n * 3; // <-- normal integer multiplication
int b = (n << 1) + n; // <-- potentially faster multiplication
最佳答案
那个说“把它留给编译器”的人是对的,但我没有“声誉”来修改他或发表评论。我让 gcc 编译 int test(int a) { return a/3; } 对于 ix86,然后反汇编输出。仅出于学术兴趣,它所做的是粗略地乘以 0x55555556,然后取其 64 位结果的前 32 位。你可以用 eg 向自己证明这一点:
$ ruby -e 'puts(60000 * 0x55555556 >> 32)' 20000 $ ruby -e 'puts(72 * 0x55555556 >> 32)' 24 $
Montgomery division 上的维基百科页面很难阅读,但幸运的是编译器已经做到了,所以你不必这样做。
关于optimization - 将整数除以 3 的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4611106/