I asked my father this question, and he gave a more efficient algorithm.
I revised my answer - but the credit goes to Bill Millard.