finished algorithm for problem 2