English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I was asked this question in an interview for a computer security company.

Q. How can you multiply by 7 without using a multiplication operator?

I said, "By adding the number 7 times in a loop.". He laughed and said, "I want a better answer." I couldn't figure out.

Any one can crack this?

2007-02-26 15:00:12 · 3 answers · asked by Anonymous in Computers & Internet Programming & Design

3 answers

Maybe he was looking for bitwise operations.
In c++, you could use the "<<" operator to leftshift all the bits, so for instance:
(2 << 3) would cause 000000010 (2) to become 00010000 (16)
Each leftshift is the equivilent of multiplying by a power of two, so 3 leftshifts would be multiplying by 8. To multiply by 7, just subtract the original number once. In the above example, 16-2=14, which is equal to 2*7. So the full equation (in c++) would be:
(x<<3)-x

2007-02-26 15:29:07 · answer #1 · answered by Tom 3 · 0 0

I think bitwise operator shifting is the solution. But I still dont understand why such questions are asked in the interview? Who the hell will want to multiply by 7 like that?

2007-02-26 23:42:01 · answer #2 · answered by manoj Ransing 3 · 0 0

"Better" is very much context dependent here. One efficient low-level algorithm is to shift left 3 bits and subtract the original value.

2007-02-26 23:21:26 · answer #3 · answered by injanier 7 · 0 0

fedest.com, questions and answers