Alex Rivera | Logout

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

Asked 2008-10-05T01:13:19.537
45
int x = n / 3;  // <-- make this faster

// for instance

int a = n * 3; // <-- normal integer multiplication

int b = (n << 1) + n; // <-- potentially faster multiplication
Edit
Report

2 Answers

61

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;
answered 2008-10-05T01:30:32.840
0

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];
}
answered 2013-07-17T06:55:33.880

Your Answer