ported previously completed problem 6 from C++