Finished Exams (194A) problem from CodeForces. Two solutions: brute force and a mathematical formula.