Fair and square from Google code jam. Tooooo slow