Efficient computation of $\sum_{k=1}^n \left\lfloor \frac{n}{k}\right\rfloor$ I realize that there is probably not a closed form, but is there an efficient way to calculate the following expression?
$$\sum_{k=1}^n \left\lfloor \frac{n}{k}\right\rfloor$$
I've noticed $$\sum_{k=1}^n \left\lfloor \frac{n}{k}\right\rfloor = \left\lfloor\frac{1}{2}\sum_{k=1}^{\left\lfloor\frac{n}{2}\right\rfloor} \left\lfloor\frac{n}{k}\right\rfloor\right\rfloor + \sum_{k=1,\ odd(k)}^n \left\lfloor \frac{n}{k}\right\rfloor$$
But I can't see an easy way to let the second term enter in a recursion.
 A: In addition to Raymond's neat formula, I found the following less neat version.
It is based on the observation that after around $\sqrt n$ terms, we start seeing a lot of repeated values. By looking at how many solutions there are to $\lfloor\frac{n}{k}\rfloor=a$ we can get an expression like:
$$\underbrace{\sum_{k=1}^{\left\lfloor\frac{n}{\left\lfloor\sqrt n\right\rfloor-1}\right\rfloor}\left\lfloor\frac{n}{k}\right\rfloor}_\text{Direct calculation of sparse values} + \underbrace{\sum_{a=1}^{\lfloor\sqrt n\rfloor}a\left(\left\lfloor\frac{n}{a}\right\rfloor-\left\lfloor\frac{n}{a+1}\right\rfloor\right)}_\text{Grouped calculation of dense values}$$
This is useful if you need to sum something more complex like $\sum_{k=1}^nk^m\left\lfloor\frac{n}{k}\right\rfloor$
A: For the initial sum see sequence A006218 from OEIS and the Wikipedia page about the 'Divisor summatory function'.
Richard Sladkey's paper 'A Successive Approximation Algorithm for Computing the Divisor Summatory Function' proposes evolutions of the classical  :
$$\sum_{k=1}^n \left\lfloor \frac{n}{k}\right\rfloor=2\sum_{k=1}^{\lfloor\sqrt{n}\rfloor} \left\lfloor \frac{n}{k}\right\rfloor-\left\lfloor\sqrt{n}\right\rfloor^2$$
(perhaps that making this recursive...)
Some other references :


*

*A corresponding answer from Rick Sladkey at S.E.

*Another [thread](A triangular representation for the divisor summatory function, $D(x)$
representation-for-the-divisor-summatory-function-dx) with javascript.

*Tao and all's paper 'Deterministic methods to find primes'
A: Your formula is wrong
With $n = 7$ we have
result $= ⌊7/1⌋ + ⌊7/2⌋ + ⌊7/3⌋ + ⌊7/4⌋ + ⌊7/5⌋ + ⌊7/6⌋ + ⌊7/7⌋$
$ = 7 + 3 + 2 + 1 + 1 + 1 + 1 = 16$
but your function give
result $= ⌊$(⌊7/1⌋ + ⌊7/2⌋ + ⌊7/3⌋)$/ 2⌋$ + (⌊7/1⌋ + ⌊7/3⌋ + ⌊7/5⌋ + ⌊7/7⌋) $= 6 + 11 = 17$
