45 ms·
You 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.
by furyofantares 15y ago
You 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).