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

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

    For really large integer division (e.g. numbers bigger than 64bit) you can represent your number as an int[] and perform division quite fast by taking two digits at a time and divide them by 3. The remainder will be part of the next two digits and so forth.

    eg. 11004 / 3 you say

    11/3 = 3, remaineder = 2 (from 11-3*3)

    20/3 = 6, remainder = 2 (from 20-6*3)

    20/3 = 6, remainder = 2 (from 20-6*3)

    24/3 = 8, remainder = 0

    hence the result 3668

    internal static List<int> Div3(int[] a)
    {
      int remainder = 0;
      var res = new List<int>();
      for (int i = 0; i < a.Length; i++)
      {
        var val = remainder + a[i];
        var div = val/3;
    
        remainder = 10*(val%3);
        if (div > 9)
        {
          res.Add(div/10);
          res.Add(div%10);
        }
        else
          res.Add(div);
      }
      if (res[0] == 0) res.RemoveAt(0);
      return res;
    }
    
    0 讨论(0)
  • 2020-11-29 03:54

    A lookup table approach would also be faster in some architectures.

    uint8_t DivBy3LU(uint8_t u8Operand)
    {
       uint8_t ai8Div3 = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, ....];
    
       return ai8Div3[u8Operand];
    }
    
    0 讨论(0)
  • 2020-11-29 04:01

    Depending on your platform and depending on your C compiler, a native solution like just using

    y = x / 3
    

    Can be fast or it can be awfully slow (even if division is done entirely in hardware, if it is done using a DIV instruction, this instruction is about 3 to 4 times slower than a multiplication on modern CPUs). Very good C compilers with optimization flags turned on may optimize this operation, but if you want to be sure, you are better off optimizing it yourself.

    For optimization it is important to have integer numbers of a known size. In C int has no known size (it can vary by platform and compiler!), so you are better using C99 fixed-size integers. The code below assumes that you want to divide an unsigned 32-bit integer by three and that you C compiler knows about 64 bit integer numbers (NOTE: Even on a 32 bit CPU architecture most C compilers can handle 64 bit integers just fine):

    static inline uint32_t divby3 (
        uint32_t divideMe
    ) {
        return (uint32_t)(((uint64_t)0xAAAAAAABULL * divideMe) >> 33);
    }
    

    As crazy as this might sound, but the method above indeed does divide by 3. All it needs for doing so is a single 64 bit multiplication and a shift (like I said, multiplications might be 3 to 4 times faster than divisions on your CPU). In a 64 bit application this code will be a lot faster than in a 32 bit application (in a 32 bit application multiplying two 64 bit numbers take 3 multiplications and 3 additions on 32 bit values) - however, it might be still faster than a division on a 32 bit machine.

    On the other hand, if your compiler is a very good one and knows the trick how to optimize integer division by a constant (latest GCC does, I just checked), it will generate the code above anyway (GCC will create exactly this code for "/3" if you enable at least optimization level 1). For other compilers... you cannot rely or expect that it will use tricks like that, even though this method is very well documented and mentioned everywhere on the Internet.

    Problem is that it only works for constant numbers, not for variable ones. You always need to know the magic number (here 0xAAAAAAAB) and the correct operations after the multiplication (shifts and/or additions in most cases) and both is different depending on the number you want to divide by and both take too much CPU time to calculate them on the fly (that would be slower than hardware division). However, it's easy for a compiler to calculate these during compile time (where one second more or less compile time plays hardly a role).

    0 讨论(0)
  • 2020-11-29 04:01

    If you really want to see this article on integer division, but it only has academic merit ... it would be an interesting application that actually needed to perform that benefited from that kind of trick.

    0 讨论(0)
  • 2020-11-29 04:12

    This is the fastest as the compiler will optimize it if it can depending on the output processor.

    int a;
    int b;
    
    a = some value;
    b = a / 3;
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题