ACM problem B with small bug