2.77 Multiple By Shifts

★★

Problem:

Suppose we are given the task of generating code to multiply integer variable x by various different constant factors K. To be efficient, we want to use only the operations +, - and <<. For the following values of K, write C expressions to perform the multiplication using at most three operations per expression.

A. K=17

B. K=-7

C. K=60

D. K=-112

Code:

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

int A(int x) {
    return x + (x << 4);
}

int B(int x) {
    return x - (x << 3);
}

int C(int x) {
    return (x << 6) - (x << 2);
}

int D(int x) {
    return (x << 4) - (x << 7);
}

int main() {
    assert(A(19) == 17 * 19);
    assert(B(19) == -7 * 19);
    assert(C(19) == 60 * 19);
    assert(D(19) == -112 * 19);
    return 0;
}

Last updated