Add a cached version.

For further experimentation added a version of the function that caches
the values.
Should outperform the iterative solution, but leaks memory.