Technique · CP 1600
Harmonic Lemma & Quotient Blocks
Two counting facts. Looping over all multiples of every d <= n costs n/1 + n/2 + ... = O(n log n). And floor(n/i) takes only O(sqrt n) distinct values, each on a contiguous block of i, so a sum of f(floor(n/i)) costs O(sqrt n).
Learn firstMath / Number Theory
0%
mastery
0/7 solved
0/7 solved
Recognise it
The signal
sum of floor(n/i) or sigma(i) up to n = 1e12
1Brute force
O(n), or O(V2) over pairs.
2The observation
Iterating every i, or every pair.
3Why it works
For i in [l, r] with r = n / (n / l), floor(n/i) is constant.
Reach for it when
- +for every d, count the multiples of d present
- +pair conditions on divisibility with values up to 1e5-1e6
Not when
- ×there is no divisibility or floor structure
Practice
0/7 solved
- Sum of DivisorsCSESMedium
- Common DivisorsCSESMedium
- Floor and ModCodeforces1700
- Counting DivisorsCSESMedium
- Orac and ModelsCodeforces1400
- Sum of Floored PairsHard
- Not AddingCodeforces1900
Pitfalls
Misconceptions
- !iterating the divisors of each element (O(V sqrt V)) instead of the multiples of each d
Go deeper1 combinations · resources
Combinations
Harmonic Lemma & Quotient Blocks+Prefix Sum
sum over pairs of floor(a_i / a_j) with values <= 1e5
- Harmonic Lemma & Quotient Blocks:
- for each divisor value d and each multiple k*d, the count of x in [k*d, (k+1)*d) contributes k
- Prefix Sum:
- counts of values in a range in O(1)