I recently encountered the following interview question:
How can you multiply a number by 7 in an efficient and optimized way?
I know that I can multiply by 8 (or left-shift by three bits) and then subtract the original value:
num = (num << 3) - num;
but are there any other solutions.
To get a multiple of 7 in an efficient way:
7 is a multiple of 7. That answers the question you asked, but I’m sure it doesn’t answer the question you mean to ask.
EDIT: The above is based on the question’s original title,which I’ve just corrected.
To multiply by 7 efficiently, just write, for example:
and invoke your compiler with optimization. Let the compiler figure out whether a single MUL instruction or something like
(x<<3) - xis more efficient for the current machine.There’s yet another implicit question here: what answer was the interviewer looking for? I hope that “let the compiler worry about it” would be an acceptable answer.
(x<<3) - xis probably the most obvious micro-optimization — but it can yield incorrect answers ifx<<3overflows, and depending on the system it might be slower than a MUL instruction.(If I were the interviewer, I’d be more impressed by a good explanation and understanding of the issues than by any specific answer.)
EDIT
On further thought, the kinds of micro-optimizations that have been discussed here might be useful if you know more about the possible values of
xthan the compiler does. If you know, because of the nature of your program’s logic, thatxwill always be in the range 0..10, then a lookup table could easily be faster than a multiply operation. Or if you know thatxis in that range 99% of the time, a lookup table with a fallback to an actual multiplication might be just the thing.But if the compiler’s analysis of your program flow doesn’t allow it to prove that
xis always in that range, then it can’t perform this kind of optimization.But such circumstances are very rare. And when your code runs in a new environment where
xcan be 11 (perhaps it’s running on a device with a larger display), kaboom. And the performance improvement very likely wasn’t significant in the first place.There are times when micro-optimization is appropriate, but there is a substantial cost in development and testing time. Do it only if actual measurements indicate that it’s worth it.