Solution for problem 36, combined code from problem 4