設 \(f(n) = \sum\limits^{n}_{i=1}{\lfloor\frac{n}{i}\rfloor}\) ,給定 \(n, n \in [1, 10^9] \cap \mathbb{Z}\) ,求 \(f(n)\)
演算法分析
當 \(n = 20\) 時,有
\(i\) | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
\(\lfloor\frac{n}{i}\rfloor\) | 20 | 10 | 6 | 5 | 4 | 3 | 2 | 2 | 2 | 2 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
可以看出有連續一塊都相同的結果。
事實上有不超過 \(2\sqrt n\) 這樣的塊個。
證明 有不超過 \(2\sqrt n\) 個這樣的塊。
引理
\(\forall a \in [2, \sqrt n - 1], \lfloor\frac{n}{a}\rfloor > \lfloor\frac{n}{a+1}\rfloor\)
證明:
反證法。顯然 \(\lfloor\frac{n}{a}\rfloor \geq \lfloor\frac{n}{a+1}\rfloor\) 。假設 \(\exists a \in [2, \sqrt n - 1], \lfloor\frac{n}{a}\rfloor = \lfloor\frac{n}{a+1}\rfloor = k \geq \sqrt n\)
\(\Rightarrow n = a \cdot k + c_1 = (a + 1) \cdot k + c_2, 0 \leq c_1 < a, 0 \leq c_2 < a + 1\)
\(\Rightarrow a \cdot k + c_1 = a \cdot k + k + c_2\)
\(\Rightarrow c_1 = k + c_2\)
\(\because k \geq \sqrt n, 0 \leq c_2\)
\(\therefore c_1 \geq \sqrt n\)
與 \(c_1 < a < \sqrt n\) 矛盾,原命題得證。
證明
在 \([1, \sqrt n] \cap \mathbb{Z}\) 中取兩個數 \(x_1, x_2\) ,且 \(x_1 + 1 = x_2\)
\(y_1 = \lfloor\frac{n}{x_1}\rfloor, y_2 = \lfloor\frac{n}{x_2}\rfloor\) ,則 \(y_2 < y_1\) , 且 \([y_2, y_1] \subseteq [\sqrt n, n]\)
對於 \([y_2 + 1, y_1]\):
-
對於上界 \(y_1\):
\(y_1 = \lfloor\frac{n}{x_1}\rfloor\)
\(\Rightarrow n = y_1 \cdot x_1 + z \Rightarrow z < x_1 < x_2 \leq \sqrt n \leq y_1 \Rightarrow z < y_1\)
\(\Rightarrow \lfloor\frac{n}{y_1}\rfloor = x_1\)
-
對於下界 \(y_2 + 1\):
\(y_2 = \lfloor\frac{n}{x_2}\rfloor\)
\(\Rightarrow n = x_2 \cdot y_2 + z, z < x_2\)
\(\Rightarrow x_2 \cdot (y_2 + 1) > n \Rightarrow x_2 > \lfloor\frac{n}{y_2 + 1}\rfloor \Rightarrow x_1 \geq \lfloor\frac{n}{y_2 + 1}\rfloor\)
\(y_2 + 1 \leq y_1 \Rightarrow \lfloor\frac{n}{y_2 + 1}\rfloor \geq \lfloor\frac{n}{y_1}\rfloor = x_1\)
\(x_1 \geq \lfloor\frac{n}{y_2 + 1}\rfloor \geq x_1 \Rightarrow \lfloor\frac{n}{y_1}\rfloor = x_1\)
綜上,\(\forall k \in [y_2 + 1, y_1], \lfloor\frac{n}{k}\rfloor = x_1\)
所以,對於 \(k \in [1, \sqrt n]\) 都有與之對應的 \(\lfloor\frac{n}{k}\rfloor \in [\sqrt n, n]\) ,反過來對於 \(k \in [\sqrt n, n]\) 都有與之對應的 \(\lfloor\frac{n}{k}\rfloor \in [1, \sqrt n]\) ,一共有 \(2\sqrt n\) 個,原命題得證。
左右邊界
設 \(l\) 為分塊左邊界,\(r\) 為分塊右邊界,\(k = \lfloor\frac{n}{l}\rfloor = \lfloor\frac{n}{r}\rfloor\) ,那麼 \(k=\lfloor \frac{n}{l} \rfloor\)。\(r\) 為 \(i\) 最大值, \(i\) 滿足 \(\lfloor\frac{n}{i}\rfloor = k\) ,\(n = k \cdot i + z, z \in [0, k) \cap \mathbb{Z}\),所以 \(i = \frac{n-z}{k}\),可得 \(i \leq \lfloor\frac{n}{k}\rfloor\),即 \(r=\max(i)=\lfloor\frac{n}{k}\rfloor\)。將 \(k = \lfloor\frac{n}{l}\rfloor\) 帶入,\(r = \lfloor \frac{n}{\lfloor\frac{n}{l}\rfloor} \rfloor\)
程式碼
int f(int n) {
int res = 0;
for(int l = 1, r; l <= n; l = r + 1)
{
r = n / (n / l);
res += n / l * (r - l + 1);
}
return res;
}