Solving problem 4 in c++