solved problem 31 in ruby