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

后端 未结 12 2119
天涯浪人
天涯浪人 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

    What if you really don't want to multiply or divide? Here is is an approximation I just invented. It works because (x/3) = (x/4) + (x/12). But since (x/12) = (x/4) / 3 we just have to repeat the process until its good enough.

    #include 
    
    void main()
    {
        int n = 1000;
        int a,b;
        a = n >> 2;
        b = (a >> 2);
        a += b;
        b = (b >> 2);
        a += b;
        b = (b >> 2);
        a += b;
        b = (b >> 2);
        a += b;
        printf("a=%d\n", a);
    }
    

    The result is 330. It could be made more accurate using b = ((b+2)>>2); to account for rounding.

    If you are allowed to multiply, just pick a suitable approximation for (1/3), with a power-of-2 divisor. For example, n * (1/3) ~= n * 43 / 128 = (n * 43) >> 7.

    This technique is most useful in Indiana.

提交回复
热议问题