solved problem 5 in ruby but answer is very slow