Correct implementation of problem23