improved speed for problem 27