if we have 2 numbers, say a and b then how can we find the value of sum of b%i where i ranges from 1 to a?
One way is to iterate through all values from 1 to a but is there any efficient method?
(better than O(n) ?)
E.g : if a = 4 and b = 5 then required ans = 5%1+5%2+5%3+5%4=4
Thanks.
if we have 2 numbers, say a and b then how can we find
Share
For
i > b, we haveb % i == b, so that part of the sum is easily calculated in constant time ((a-b)*b, ifa >= b, 0 otherwise).The part for
i <= bremains to be calculated (i == bgives 0, thus may be ignored). You can do that in O(sqrt(b)) steps,i <= sqrt(b), calculateb % iand add to sumi > sqrt(b), letk = floor(b/i), thenb % i == b - k*i, andk < sqrt(b). So fork = 1toceiling(sqrt(b))-1, lethi = floor(b/k)andlo = floor(b/(k+1)). There arehi - lonumbersisuch thatk*i <= b < (k+1)*i, the sum ofb % ifor them issum_{ lo < i <= hi } (b - k*i) = (hi - lo)*b - k*(hi-lo)*(hi+lo+1)/2.If
a <= sqrt(b), only the first bullet applies, stopping ata. Ifsqrt(b) < a < b, in the second bullet, run fromk = floor(b/a)toceiling(sqrt(b))-1and adjust the upper limit for the smallestktoa.Overall complexity O(min(a,sqrt(b))).
Code (C):