How to write a function countTo(n) that counts from 1 to n and prints each number without using explicit loops (only recursion)?
The solution must be asymptotically optimal in space and time, even without tail call optimisation, given arbitrarily big n.
Note: the optimal time complexity is O(1) while the optimal space complexity is O(log n) – even in the iterative case, since the (arbitrarily large) number needs to be printed.
The question comes from lesswrong.com, and the relevant details are taken from the discussion there (otherwise the question becomes impossible to answer since their original statement makes misleading assumptions).
If you want the rewritten version to still be recursive, there is no way. Any function call will consume stack space.
There are languages in which calls that are in a tail position will not consume stack space. In such languages you could rewrite your function to be tail-recursive, so it would run in O(1) space. However Python is not one of those languages.