Search~15 min2s · 256 MBtarget O(log limit) time, O(1) spacecomplexity
A search box looks up a term in an index of n entries. One index design splits the range in two at every level, and another splits it in ten at every level. Each level costs one step.
The number of levels for a size n is how many times n can be divided by the split, rounding down, while it is at least the split. The team wants to know how many more levels the two-way design needs than the ten-way design, added up over every size from 1 to a limit.
Write total_extra_levels(limit).
levels(n, b) is the number of times you can replace n by n // b while n >= b, starting from n.n from 1 to limit, take levels(n, 2) - levels(n, 10).Input: limit = 12
Output: 22Each row is one size n. levels(n, b) is how many times n can be divided by b while it stays at least b.
| n | Two-way levels | Ten-way levels | Extra |
|---|---|---|---|
| 1 | 0 | 0 | 0 |
| 2, 3 | 1 | 0 | 1 each |
| 4 to 7 | 2 | 0 | 2 each |
| 8, 9 | 3 | 0 | 3 each |
| 10 to 12 | 3 | 1 | 2 each |
The extras add up to 0 + 2 + 8 + 6 + 6 = 22.
Input: limit = 100
Output: 388Summed over the sizes 1 to 100, the two-way index needs 388 more levels than the ten-way index.
Input: limit = 1
Output: 0Size 1 needs no level in either index, so the total is 0.
1 ≤ limit ≤ 1,000,000,000 (the largest index size)Running both loops for every size takes about 10^10 passes at the top limit, which is too slow. The answer reaches about 2 × 10^10, so it needs a 64-bit integer. Count the sizes that need each level instead.