Improved solution to Problem 5 (runtime halved)