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

后端 未结 12 2145
天涯浪人
天涯浪人 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 03:53

    I don't know if it's faster but if you want to use a bitwise operator to perform binary division you can use the shift and subtract method described at this page:

    • Set quotient to 0
    • Align leftmost digits in dividend and divisor
    • Repeat:
      • If that portion of the dividend above the divisor is greater than or equal to the divisor:
        • Then subtract divisor from that portion of the dividend and
        • Concatentate 1 to the right hand end of the quotient
        • Else concatentate 0 to the right hand end of the quotient
      • Shift the divisor one place right
    • Until dividend is less than the divisor:
    • quotient is correct, dividend is remainder
    • STOP

提交回复
热议问题