Implementation of problem 17 but seems to have a bug