Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

The OPs example blows my mind but not in the way originally intended. Wow, it managed to make a trivial constant-time operation into an exponential-time operation. This is a mind-blowingly bad example of recursion.

It's like trying to enter a house by demolishing it and rebuilding it around you instead of opening the door and walking in.



How is it exponential time? It should be linear as it loops through at most `n` times. My guess is that it would also be optimized for tail recursion so it wouldn't clobber the call stack either.

That said - you're right that it's still slower than constant time


Because it only takes log(n) digits to represent n.

9 is 1 digit, takes 9 steps.

99 is 2 digits, takes 99 steps.

999 is 3 digits, takes 999 steps.

An input d decimal digits long takes O(10^d) steps.

The runtime is exponential in the "size of the input", because the size of the input is usually taken to be the length of the binary or decimal representation of the number rather than the magnitude of the number.




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

Search: