For i > b we have b % i == b , so that part of the sum is easily calculated in constant time ( (ab)*b if a >= b , 0 otherwise).
The part for i <= b remains calculated ( i == b gives 0, so it can be ignored). You can do this in steps O (sqrt (b))
- For
i <= sqrt(b) calculate b % i and add to the sum - For
i > sqrt(b) , k = floor(b/i) , then b % i == b - k*i and k < sqrt(b) . So, for k = 1 to ceiling(sqrt(b))-1 , hi = floor(b/k) and lo = floor(b/(k+1)) . There are hi - lo numbers i such that k*i <= b < (k+1)*i , the sum b % i for them is sum_{ lo < i <= hi } (b - k*i) = (hi - lo)*b - k*(hi-lo)*(hi+lo+1)/2 .
If a <= sqrt(b) , only the first bullet is applied, stopping at a . If sqrt(b) < a < b , in the second pool, run from k = floor(b/a) to ceiling(sqrt(b))-1 and adjust the upper limit for the smallest k to a .
The total complexity is O (min (a, sqrt (b))).
Code (C):
#include <stdlib.h>
source share