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

后端 未结 12 2139
天涯浪人
天涯浪人 2020-11-29 03:40
int x = n / 3;  // <-- make this faster

// for instance

int a = n * 3; // <-- normal integer multiplication

int b = (n << 1) + n; // <-- potentiall         


        
12条回答
  •  悲&欢浪女
    2020-11-29 04:13

    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.

提交回复
热议问题