Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Math & Number Theory/Math / Number Theory

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
Practise nextSum of Divisors
IdeaPracticePitfalls

Recognise it

The signal

sum of floor(n/i) or sigma(i) up to n = 1e12

  1. 1Brute force

    O(n), or O(V2) over pairs.

  2. 2The observation

    Iterating every i, or every pair.

  3. 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

Next

Sum of Divisors

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)

    Sum of Floored Pairs

Resources

  • Binary exponentiationcp-algorithms · article
  • Sieve of Eratosthenescp-algorithms · article
  • Modular inversecp-algorithms · article
  • DivisibilityUSACO Guide · course
  • CombinatoricsUSACO Guide · course
  • Math cheatsheetTech Interview Handbook · article
TodayReviewPatternsProblems