Improved problem 5 solution