Another way would be to use memorization. Just use the same recursive way but everytime that you're about to compute the answer, first check if the answer is in a cache that you have prepared. If yes, use that. If not, recurse. And when you get an answer, put it in the cache. That's memoization. It will run in O(n) time but also use O(n) space for the cache.
Doesn't this ignore cache update and lookup times? I guess O(n_max) (n->infinity makes that hard) would have plain array indexed with n, but otherwise you end with at least multiples of n. And there is a loop or tail recursion that has O(n) time and constant memory use anyway. Point of memoization is that after first time, its cache fetch complexity rather than original complexity, O(1) if we have enough memory and trivial index, and you can do that with the loop and tail recursion as well.
View all comments
Show parent comment
1
u/Xywzel 1d ago
Doesn't this ignore cache update and lookup times? I guess O(n_max) (n->infinity makes that hard) would have plain array indexed with n, but otherwise you end with at least multiples of n. And there is a loop or tail recursion that has O(n) time and constant memory use anyway. Point of memoization is that after first time, its cache fetch complexity rather than original complexity, O(1) if we have enough memory and trivial index, and you can do that with the loop and tail recursion as well.