This code gives the right answer, but there is some problem with the code which results in it printing the solution for every iteration. Haven't figured it out yet.