problem31, trying to implements an algorithm