Multiply By seven [closed]
I was asked this interview question:
what is the quickest way to multiply a number by 7.
she told me not to use any of the + , - , * , /
operators.
In tense,i could not answer the question.
I know the quickest way to multiply a number by 8 is n<<3
but can n*7
be acheived?
Assuming your compiler isn't terrible, n*7
.
Meets almost all your requirements :)
#include <stdio.h>
int mult7(int i)
{
int res;
__asm__("imull $7, %1, %0" : "=r" (res) : "r" (i));
return res;
}
int main()
{
printf("%d", mult7(12)); //output: 84
return 0;
}
No forbidden operators (+
, -
, *
, or /
) used :)
/* multiply by 7 without using the forbidden operators */
/* if `n` is larger than `INT_MAX / 7`
** or smaller than `INT_MIN / 7`
** the behaviour is undefined. */
int mult7(int n) {
int n7 = n;
n7 *= 7;
return n7;
}
n*7 == (n<<3) - n
Not sure if that will be better then normal multiplication by 7 though
The correct answer is a combination of
a) n*7
because this is exactly the kind of micro-optimization that the compiler is perfectly capable of figuring out on its own.
b) the interviewer has a poor understanding of modern optimizing compilers
Alternatively, if the interviewer isn't clueless, an answer different than a) above suggests that the interviewee does not understand optimizing compilers and is thus a poor candidate for the job. :-/
The best answer I can come up with is to write "+" operation using while loop and bitwise operators per each bit. Something like this:
int add(int x, int y) {
int a, b;
do {
a = x & y; b = x ^ y; x = a << 1; y = b;
}while(a);
return b;
}
And then sum up n, n << 1, n << 2.
"+" is easy to write with while loop, if you can come up with way to write "-" with while loop (which i am not sure how to do exactly) than you can do (n << 3) - n.
source:http://geeki.wordpress.com/2007/12/12/adding-two-numbers-with-bitwise-and-shift-operators/
It's likely either
n*7
or
(n<<3) - n
Maybe this is a valid answer as well : pow(10, log10(n) + log10(7))
oh you were so close!
= (n << 3 - n)
= n * 8 - n
= n(8 - 1)
= n * 7
Assuming that the interviewer is looking for a shift-and-add kinda answer, I guess you could use:
int ans = (num<<2) + (num<<1) + num;
I guess this a crude way of testing if the interviewee knows of this particular algo.
int main()
{
int i;
int x;
int n;
x = n;
for (i = 2; i < 8; i++)
{
n += x;
}
return 0;
}
EDIT: converted to c (i think) and realized there is no .= in c so had to switch to +=. Still not the same as + technically but a bit questionable.
I know it uses the ++ but that certainly not the same as "+" and .= avoids the stipulation.
精彩评论