Commented the logic of problem 5