2.79 Mul3div4

★★

Problem:

Write code for a function mul3div4 that, for integer argument x, computes 3*x/4. Your code should replicate the fact that the computation 3*x can cause overflow.

Code:

#include <stdio.h>
#include <assert.h>
#include <limits.h>

int mul3div4(int x) {
    x = (x << 1) + x;
    int neg_flag = x & INT_MIN;
    neg_flag && (x = x + 3);
    return x >> 2;
}

int main() {
    int x = 0xF0000000;
    assert(mul3div4(x) == x*3/4);
    return 0;
}

Last updated