a highly optimized solution to problem 5