Solution for problem 14, caching intermediate results.