improved efficiency of problem 9