ported previously completed problem 5 from C++