Alternate solution to problem #22

A far better solution by doublefelix.