fixed the algorithm and output format