5

Is there a better way to get the summation of $$\sum\limits_{i=1}^n\left\lfloor\frac ni\right\rfloor$$ I would like to know a way that is better than the complexity of $O(n)$ ... because there seems to be a pattern in the way all the floor values decrease .

This is a code that does it in less than O(n) complexity but I am unable to prove it why it works

        long long N;
        cin >> N;
        long long K = 1, mn = N, mx, sum = 0;;
        while (mn > 0)
        {
            K = N / mn;
            mx = N / K;
            mn = N / (K + 1);           
            sum += (mx - mn)*K;
        }
bsbb4
  • 3,751

1 Answers1

1

Here is my attempt to explain the idea behind the code snippet. We group equal terms in the sum: $$\sum_{i=1}^{n}\lfloor n/i\rfloor=\sum_{k=1}^{n}ka_k,$$ where $a_k$ is the number of integers $i$ such that $\lfloor n/i\rfloor=k$. Quoting my answer, we have $$\left\lfloor\frac{n}{i}\right\rfloor=k\quad\text{if and only if}\quad\left\lfloor\frac{n}{k+1}\right\rfloor<i\leqslant\left\lfloor\frac{n}{k}\right\rfloor.$$ This means that, starting with $k=1$, we have $a_k=\lfloor n/k\rfloor-\lfloor n/(k+1)\rfloor$, and the next value of $k$, such that $\color{red}{a_k\neq 0}$, is equal to $\lfloor n/i\rfloor$ at $i=\lfloor n/(k+1)\rfloor$. This is exactly what the code does exploit: for each $k$, it computes $a_k$, accumulates the sum of $ka_k$, and computes the next "useful" $k$ until there's none.

metamorphy
  • 43,591