Problems > Sum of Remainders > Editorial

Sum of Remainders — Solution & Editorial

Back to the Problem

N mod i = N − i·⌊N/i⌋, so the sum is N·M − ∑ i·⌊N/i⌋. The floor is constant over √N blocks; sum i over each block with the arithmetic-series formula.

Complexity: O(√N)

Watch out: An O(M) loop dies at 1012; the divisor-block decomposition with arithmetic sums is required.