2.80 Three Fourths

★★★

Problem:

Write code for a function threefourths which, for integer argument x, computes the value of 3/4*x, rounded toward zero. It should not overflow.

Code:

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

/*
 * 3*x/4 should not overflow, then divide 4 first, and multiple 3
 * Rounding to zero:
 *		x is equal to m30(the most significant 30 bits) plus l2(the least significant 2 bits)
 *		x = m30 + l2
 *		m30 = x & ~0x3;
 *		l2 = x & 0x3;
 *		when x >= 0, m30d4m3 = (m30 >> 2) << 1 + (m30 >> 2), l2m3d4 = ((l2 << 1) + l2) >> 2;
 *		when x < 0, need bias, bias = 3
 */
int threefourths(int x) {
    int neg_flag = x & INT_MIN;
    int m30 = x & ~0x3;
    int l2 = x & 0x3;
    int m30d4m3 = ((m30 >> 2) << 1) + (m30 >> 2);
    int bias = 3;
    int l2m3 = (l2 << 1) + l2;
    (neg_flag) && (l2m3 = l2m3 + bias);
    int l2m3d4 = l2m3 >> 2;
    return m30d4m3 + l2m3d4;
}

int main() {
    assert(threeforths(8) == 6);
  	assert(threeforths(9) == 6);
  	assert(threeforths(10) == 7);
  	assert(threeforths(11) == 8);
  	assert(threeforths(12) == 9);

  	assert(threeforths(-8) == -6);
  	assert(threeforths(-9) == -6);
  	assert(threeforths(-10) == -7);
  	assert(threeforths(-11) == -8);
  	assert(threeforths(-12) == -9);
    return 0;
}

Last updated