C++ version of Problem 1