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

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

    Easy computation ... at most n iterations where n is your number of bits:

    uint8_t divideby3(uint8_t x)
    {
      uint8_t answer =0;
      do
      {
        x>>=1;
        answer+=x;
        x=-x;
      }while(x);
      return answer;
    }
    

提交回复
热议问题