Solves Problem 5 in C++