AdvancedMath for DSAUsed everywhere

n/1 + n/2 + n/3 + … ≈ n ln n

Looping over multiples of every i up to n costs n/1 + n/2 + … ≈ n log n, not n². It's why the and “all divisors” loops are fast.

The idea

1 + 1/2 + 1/3 + … + 1/n (the harmonic series) grows like ln n, about 2.3 × log₁₀ n. So a loop where step i does n/i work costs about n ln n in total.

Typical shape: for i in 1..n, for j in i, 2i, 3i, … ≤ n. It looks nested and , but each i only visits n/i multiples.

Worked example

Count the divisors of every number up to n = 6

  1. i = 1 touches 1..6 (6), i = 2 touches 2, 4, 6 (3), i = 3 → 3, 6 (2), i = 4, 5, 6 → 1 each.
  2. Total 6 + 3 + 2 + 1 + 1 + 1 = 14 steps, close to 6 × (1 + 1/2 + … + 1/6) ≈ 14.7.
  3. For n = 10⁶ it's about 14 million steps, not 10¹².

Pseudocode

The steps in plain words. ← means “set to”; indentation shows what's inside what.

count ← 0 for 0 … n
for i from 1 to n:
for multiple from i to n, step i:(about n / i steps)
count[multiple] ← count[multiple] + 1
total steps ≈ n × (1 + 1/2 + … + 1/n) ≈ n ln n

See it run

The worked example, step by step, beside the Python. The highlighted line is the one running.

Step-by-step

n = 6

count (index = number)

00
10
20
30
40
50
60
steps = 0

Solution · Pythonline 2

def divisor_counts(n):
count = [0] * (n + 1)
for i in range(1, n + 1):
for multiple in range(i, n + 1, i): # n / i steps
count[multiple] += 1
return count # divisor_counts(6)[6] == 4

Step 1 of 8· line 2

Instead of testing every pair, let each i walk its own multiples: i, 2i, 3i… The inner loop runs n / i times.

total.

How to spot it

  • Loops over multiples (sieves, divisor sums), or step sizes that grow with the outer index.

Common mistakes

  • Rejecting a correct idea because two loops look O(n²).
  • Confusing it with 1 + 2 + … + n, which is n²/2.

Where it comes up

Go further