Div II, 500 points (Suboptimal solution)

Naive approach.  Generates correct output, but is not performance efficient and fails to terminate in <2 seconds for all inputs.