rewrite uva algorithm code