Solves Problem 8 in C++