Improved solution to problem #9 (faster by an order of magnitude)