Much more efficient version of Problem 50