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?
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?
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.
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;
}