Solution by Nick Logan
