1464. Harmonic Floor Total
A ferry company hands out one boarding token for every whole group of i passengers that fits among n waiting passengers, and it does this for every group size i from 1 to n. A group size i therefore yields floor(n / i) tokens.
Given n, return the total number of tokens, that is the sum of floor(n / i) over all i from 1 to n. The result always fits in a signed 64-bit integer. Looping over every i is far too slow for the largest n; the intended solution runs in O(sqrt(n)) time with O(1) extra space.
Example 1
- Input:
- n = 1
- Output:
- 1
- Explanation:
Only i = 1 contributes, giving floor(1 / 1) = 1 token.
Example 2
- Input:
- n = 6
- Output:
- 14
- Explanation:
The terms are 6, 3, 2, 1, 1, 1 which add up to 14.
Example 3
- Input:
- n = 10
- Output:
- 27
- Explanation:
The terms are 10, 5, 3, 2, 2, 1, 1, 1, 1, 1 which add up to 27.
Constraints
1 ≤ n ≤ 1012
The answer is below 3*1013.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(sqrt(n))
- Space
- O(1)