2 ms·
Returning 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 t
by tzs 15y ago
Returning 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.