More efficient version to problem 5