Given range x, y. I need to count all numbers in between and are divisible by n.
I know the simple way to do this is by looping over the whole range
for(int i=x;i<=y;i++) if(i%n ==0) counter++;
The counter holds the answer.
But this works so slow for big ranges. for example x=0 , and y=3,000,000,000.
I’m sure that there is some relation that I can use to reduce the number of iteration and optimizing this code for speed. I searched but i could not find it out. Can any one help me with that please.
Thanks so much.
This works:
(e+1 - s) / d + (e%d < (s+d-1)%d). (It uses C semantics and integer arithmetic and assumes the start is non-negative. s is the start value, e is the end value [inclusive], and d is the divisor.)Updated: A better solution is
e/d - (s-1)/d. This was inspired by User448810. That requires s be positive; handling zero or negative s (or e) requires adjusting for the truncation toward zero (we would want toward negative infinity for this problem).Update for negative values: The following works for any values of s and e in the range of their types, provided s <= e and 0 < d:
Essentially, the first two statements are equivalent to
e = e/dands = (s-1)/dwith the division modified to round toward -infinity instead of toward zero (so that -1/10 produces -1 rather than 0).