Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

optimize code to get the number of integers within given range that are divisible by integer

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.

like image 424
Coder Stacker Avatar asked Nov 13 '22 01:11

Coder Stacker


2 Answers

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:

e = e <  0 ? (e+1)/d - 1 : e/d;
s = s <= 0 ? s/d - 1 : (s-1)/d;
return e-s;

Essentially, the first two statements are equivalent to e = e/d and s = (s-1)/d with the division modified to round toward -infinity instead of toward zero (so that -1/10 produces -1 rather than 0).

like image 67
Eric Postpischil Avatar answered Nov 30 '22 23:11

Eric Postpischil


(floor)(high/d) - (floor)(low/d) - (high%d==0)

Explanation:

There are a/d numbers divisible by d from 0 to a. (d!=0)

Therefore (floor)(high/d) - (floor)(low/d) will give numbers divisible in the range (low,high] (Note that low is excluded and high is included in this range)

Now to remove high from the range just subtract (high%d==0)

Use fmodf for floats.

like image 37
cegprakash Avatar answered Nov 30 '22 22:11

cegprakash