0

On a homework assignment, one of the questions asked us to multiply any arbitrary integer by a constant using only the +, -, and << operators and a maximum of three operations. For example, the first constant was 17, which I solved as

(x << 4) + x

However, some of the constants given were negative (such as -7). Multiplying by 7 is a relatively trivial thing to do (I have it as (x << 3) - x), but I cannot figure out how to flip the sign using only the three allowed operators.

I have attempted to flip that bit by adding or subtracting 2147483648 to every result (with the idea that this would force the most significant bit to be used, thus flipping the sign), but in my test implementation in C#, this has proven unsuccessful.

Is there some positive number by which I can multiply a given int that will be functionally analogous to -7? Would adding 2147483648 work in a language other than C#? Am I overlooking something?

The original question from the book is below:

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

Chimera
  • 5,884
  • 7
  • 49
  • 81
bionicOnion
  • 1,494
  • 3
  • 16
  • 25

2 Answers2

2

You don't need to change the sign. You wrote 7 * x as (equivalent to) 8*x - x. Now, what do you need to do with that to obtain -7 * x?

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
1

Is x - (x << 3) not valid?

bluish
  • 26,356
  • 27
  • 122
  • 180
Kevin Tran
  • 80
  • 2