edit: added emphasis
edit: added emphasis
However, as you note, it also returns 1 for negative n, and that is just wrong.
Well, wait a second....actually, if it were a machine where integer division rounds up[1], so that 1/k = 1 for k > 1, then #3 would correctly compute x^n for n < 0. Does this safe the author's answer?
Nope!
Their code for n > 0 would fail on such a machine. They are relying on repeated division by 2 eventually resulting in 0 in order to terminate the recursion. On a round up machine, repeated division converges to 1, not 0.
[1] I'm assuming that rounding behavior of integer division is implementation defined in C as defined at the time that quiz was written.
int foo(int x, int n);
This cannot be x^n, nor n^x or x*n.I'm not sure what you want me to propose a fix for. If we want a function that calculates x^n we'd probably wouldn't write it anything like this, and we would probably return a double and accept some inaccuracy.
Presumably what we actually want is an example of a hard to read function that calculates a simple result so we can use it on an amusing quiz. In that case we could change it to take unsigned n and ask what it computes in the cases where there isn't overflow. Or even better, it would be neat if there is a reasonably small modification that could be made so that it would calculate x^n mod (2^32-1).