Completed Problem 51, it could do with some optimisation though, takes a while to execute