Funny I had just solved this question on UVA about 3 days ago. Your algorithm is correct to a point, but not quite because you have not understood the question. For example, there is supposed to be an output for every input you are given, so that break statement is not supposed to be there.