Solves Problem 6 in C++