Accepted solution to problem 245a on CodeForces