October 25, 2024
Chicago 12, Melborne City, USA
C#

Preventing overflow when multiplying by fractions


i tried to multiply integer with (17/64) rounded down, but i cannot handle overflow. (i am limited to only bitwise operators ( ~ & | << >> ! + )

#include <stdio.h>

int mulfrac(int x) {
    int mul17 = (x<<4) + x;
    int bias = (mul17 >> 31) & 63;
    int result = (mul17 + bias) >> 6;
    return result;

}

int main() {
    int test_values[] = {0, 1, -1, 3, -3, 17, -17, 11, -11, 64, -64, 128, -128, 100, -100, 400, 15, -6, 1234523590, -10000000, -10};
    int n_tests = sizeof(test_values) / sizeof(test_values[0]);

    for (int i = 0; i < n_tests; i++) {
        int x = test_values[i];
        int result = mulfrac(x);
        printf("mul_17_div_64(%d) = %d\n", x, result);
    }

    return 0;
}

I dont know how to do since I have tried different stuff but to no avail. I can not use if and while either



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video