For a given $n$ , calculate $\sum_{i=1}^{n}{\lfloor \frac{n}{i} \rfloor}$

The main idea of this problem is there are maximum $2\sqrt{n}$ different values of $\lfloor \frac{n}{i} \rfloor$. [This is also known as Harmonic lemma]

[But why?]

Now, we will only iterate over those unique values of $\lfloor \frac{n}{i} \rfloor$.

How can we do it?


for (int i = 1, j, v; i <= n && (j = n / (v = (n / i))); i = j + 1) {
	// all value x in range [i,j] will have same value floor(n/x) = v
}

Reference:

Similar Problems: