0

For example, when NOT working with integer division the following is true

x/4 + x/2 = x*(1/4+1/2) = x * 3/4

When dealing with integer division is there a way to reduce x/4 + x/2 into this form: x * (int1/int2)? If so, how?

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • This is off-topic; try at http://math.stackexchange.com. – Oliver Charlesworth Jun 08 '13 at 19:13
  • But the answer is: no. If x = 4, then then result is 3. Which cannot be obtained as the result of a single integer multiplication or division. – Oliver Charlesworth Jun 08 '13 at 19:15
  • 2
    `(x * 3)/ 4` gets you the right result and only does a single division, but it isn't in exactly the form you asked. – Adam Rosenfield Jun 08 '13 at 19:16
  • 2
    @AdamRosenfield: It doesn't, though, since (3*3)/4 = 2 while 3/4+3/2 = 0+1 = 1. – tmyklebu Jun 08 '13 at 21:19
  • you could, but it would be ridiculously complicated. Basically, the integer division is truncating any remainder, so you could do that yourself, something like (x - x % 4) /4 + (x - x % 2) / 2 ... you could work that around to x * 3 / 4 - (x % 4 + 2 * x % 2) / 4 ... check my math (I think I got it wrong) but the point is it's more of a pain than its worth. – sea-rob Jun 09 '13 at 20:35

2 Answers2

0

I don't think you'll be able to do this. Take for example

5 \ 3 + 5 \ 2 = 1 + 2 = 3

where \ denotes integer division.

Now look at the same expression with regular division

a / b + a / c = a(b + c) / bc

If we were to try to apply this rule to the example above, substituting \ for /, we would get this:

5 \ 3 + 5 \ 2 = 5(3 + 2) \ (2 * 3) = 25 \ 6 = 4 [wrong answer!]
             ^^^
     This must be wrong

I'm not trying to make the claim that there doesn't exist some identity similar to this that is correct.

Timothy Shields
  • 75,459
  • 18
  • 120
  • 173
0

The question reduce x/4 + x/2 into this form: x * (int1/int2) appears to be not quite the query you want. Forcing the (int1/int2) division first simple results in int3.

So let's work with
reduce x/4 + x/2 into this form: (x * int1)/int2

As others have mentioned, there are issues with this that hints to its impossibility. So I'll propose yet another form that might work for you in that it is still one access to x and no branching.

reduce x/4 + x/2 into this form: ((x/int1)*int2)/int3

x/4 + x/2 reduces to ((x/2)*3)/2. It takes advantage that 4 is a multiple of 2.

Note: There remains a possibility of overflow for large |x| beginning with INTMAX/3*2 or so.


Test code

int test2(int x) {
  int y1 = x/4 + x/2;
  int y2 = ((x/2)*3)/2;
  printf("%3d %3d %3d %d\n", x, y1, y2, y1==y2);
  return y1==y2;
  }
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256