Optimize solution to problem 16