Hacker News new | past | comments | ask | show | jobs | submit login

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.



"You could have ruled it out from the function signature alone" - kindly elaborate.


The return type is too small


OK. you mean result might overflow. Can't we handle it somehow? like a flag or something.. what solution(different function signature) do you propose?


My 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).




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: