Non recursive solution to problem 1