I have three numbers x, y , z.
For a range between numbers x and y.
How can i find the total numbers whose % with z is 0 i.e. how many numbers between x and y are divisible by z ?
A number is divisible by another number if it can be divided equally by that number; that is, if it yields a whole number when divided by that number. For example, 6 is divisible by 3 (we say "3 divides 6") because 6/3 = 2, and 2 is a whole number.
So, the count of such numbers is N / 2520.
In Python, the remainder operator (“%”) is used to check the divisibility of a number with 5. If the number%5 == 0, then it will be divisible.
Thus including 20 and 300 it has 60−4+1=57 multiples. If suppose instead of 300, you had x on the end where x is not a multiple of 5 then you just take first multiple of 5 when you start walking left on integer line from x, i.e. if x=304, you replace it by 300 again.
It can be done in O(1): find the first one, find the last one, find the count of all other.
I'm assuming the range is inclusive. If your ranges are exclusive, adjust the bounds by one:
find the first value after x
that is divisible by z
. You can discard x
:
x_mod = x % z; if(x_mod != 0) x += (z - x_mod);
find the last value before y
that is divisible by y
. You can discard y
:
y -= y % z;
find the size of this range:
if(x > y) return 0; else return (y - x) / z + 1;
If mathematical floor
and ceil
functions are available, the first two parts can be written more readably. Also the last part can be compressed using math functions:
x = ceil (x, z); y = floor (y, z); return max((y - x) / z + 1, 0);
if the input is guaranteed to be a valid range (x >= y
), the last test or max
is unneccessary:
x = ceil (x, z); y = floor (y, z); return (y - x) / z + 1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With