Tail recursive solution for problem 2