UVa 10830 - A New Function

10830 - A New Function

 * http://acm.uva.es/p/v108/10830.html

Summary
Given a number $$N$$, find the cumulative sum of all the divisors of all numbers $$\leq N$$, excluding 1 and the number itself.

Explanation
A number $$d$$ appears $$\lfloor N/d \rfloor$$ times as a divisor of the numbers $$1 \ldots N$$. (Try it on paper if you don't see this) Because the number itself should not be counted, we have to substract 1 from this. This leads to this algorithm: $$\sum_{2\le d\le N}d(\lfloor \frac{N}{d} \rfloor-1)$$. This formula gives the right results, but is way to slow.

When studying the sequence of values for $$\lfloor N/d \rfloor$$, we see that it is decreasing and that (especially at the end) the values are the same for quite a long time. Given $$l$$, we can binary search on the last value $$h$$, for which $$\lfloor N/l \rfloor =\lfloor N/h \rfloor$$. So

$$\sum_{l\le d\le h}d(\lfloor N/d \rfloor-1)$$

$$=\sum_{l\le d\le h}d(\lfloor N/l \rfloor -1)$$

$$=(\lfloor N/l \rfloor -1)\sum_{l\le d\le h}d$$

$$=(\lfloor N/l \rfloor -1)\frac{1}{2}(h-l+1)(l+h)$$. If we binary search in $$[l\ldots N]$$ it is still gets TLE. But if we tweak the upper bound, using the observation that $$h-l$$ usually doesn't change much for two adjacent intervals, we can get AC.

Gotcha's
Watch out for overflows, especially in the binary search: $$m=\frac{l+h}{2}$$ can overflow if you use ints!

Input
2 100 200000000 0

Output
Case 1: 0 Case 2: 3150 Case 3: 12898681201837053