What is there to debug? Pay attention to what the loops are doing. Work through this by hand, with a piece of paper and a pencil, to get a better idea of what's going on.