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

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

    For 64 bit numbers:

    uint64_t divBy3(uint64_t x)
    {
        return x*12297829382473034411ULL;
    }
    

    However this isn't the truncating integer division you might expect. It works correctly if the number is already divisible by 3, but it returns a huge number if it isn't.

    For example if you run it on for example 11, it returns 6148914691236517209. This looks like a garbage but it's in fact the correct answer: multiply it by 3 and you get back the 11!

    If you are looking for the truncating division, then just use the / operator. I highly doubt you can get much faster than that.

    Theory:

    64 bit unsigned arithmetic is a modulo 2^64 arithmetic. This means for each integer which is coprime with the 2^64 modulus (essentially all odd numbers) there exists a multiplicative inverse which you can use to multiply with instead of division. This magic number can be obtained by solving the 3*x + 2^64*y = 1 equation using the Extended Euclidean Algorithm.

提交回复
热议问题