Solves Problem 4 in C++