P044: improved solution by caching results