Alex Rivera | Logout

Multiply by 7 in efficient way

Asked 2011-11-03T07:14:05.797
9

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.

c
Edit
Report

1 Answer

4

In fact, the most efficient way to multiply by 7 may be to use the multiply operator. It depends on the relative speed of the respective instructions on the target platform.

IMO, a complete answer to such an interview question should also mention the following:

  1. This kind of optimization is normally best left to the compiler / compiler writer. (Indeed, from another answer, it appears that gcc does optimize this case.)

  2. You (as a programmer) should only spend time on this if 1) there is a real (measurable) performance issue, and 2) your profiler tells you that the statements that you are looking at are performance critical.


In his answer. Olaf wrote this:

"I disagree with Stephen C when he tells you what you should (or shouldn't) do. If everyone did that there'd be no innovations in the software industry."

It would seem that Olaf that doesn't believe one or more of the following:

  • that a Software Engineer should give advice,
  • that a Software Engineer should take advice, or
  • that an employee/programmer should avoid wasting the bosses time on pointless hand-optimization.

It is true that if everyone always acted on the advice they received there would be less innovation. But the flip side is that the job in hand typically does not require much innovation. (And it rarely requires hand optimization ...)

Besides, if ignoring advice (best practice) was a virtue, then 75% of software engineers would be spending their time maintaining "goto spaghetti", assembly code or the results of some 1990's fad in design methodology.

So you should at the very least understand the advice, and weigh up the potential consequences of ignoring it. Like the boss taking a dim view of your "innovating" (or more accurately, time wasting) on his projects.

answered 2011-11-03T07:21:31.680

Your Answer