4 ms·
Stopped at #3. It seems incorrect. The answer states that foo returns x to the power of n. But I ruled that answer out since any 0 or negative n is going to
by grannyg00se 15y ago
Stopped at #3. It seems incorrect. The answer states that foo returns x to the power of n. But I ruled that answer out since any 0 or negative n is going to return 1.
edit: added emphasis
- tzs 15y agoReturning 1 for n = 0 is OK, as x^0 = 1 for all non-zero x, and 0^0 is usually also defined as 1. 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.
- furyofantares 15y agoYou could have ruled it out from the function signature alone: int foo(int x, int n); This cannot be x^n, nor n^x or x*n.
- raviksharma 15y ago"You could have ruled it out from the function signature alone" - kindly elaborate.
- furyofantares 15y agoThe return type is too small
- raviksharma 15y agoOK. you mean result might overflow. Can't we handle it somehow? like a flag or something.. what solution(different function signature) do you propose?
- furyofantares 15y agoMy point was just that if you want to nitpick that it isn't x^n for all inputs, then the n < 0 cases are only a part of the problem since foo(10,10) can't possibly be 10^10 regardless of the the function's body. 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).