Refactoring problem 4 to reduce number of iterations