Much more efficient version for Problem 5