Formula for numbers divisible in an interval

ceiling-and-floor-functionsdivisibility

Assume we have three natural numbers $x$, $y$, and $z$, with $z>y>x$.

I want to find a formula, which gives us the number of natural numbers divisible by $x$, in the interval $[y,z]$.

From some observation, I got the formula

$$N=\Big\lfloor\frac zx\Big\rfloor-\Big\lfloor \frac yx\Big\rfloor$$

This was working pretty good…

$$\begin{align}[100,999]÷3&=300 \\ [100,999]÷6&=150 \\ [100,999]÷42&=21\end{align}$$

…until it didn't.

$$[100,999]÷2=450$$

whereas the formula gives $449$.

I think this error is because $100$ is already divisible by $2$.

My question is how can I modify the formula so that that I can account for the case where $y$ is already divisible by $x$. It seems that for such cases

$$N=\Big\lfloor\frac zx\Big\rfloor-\Big\lfloor\frac yx\Big\rfloor+1$$

works, but I would prefer a formula which accounts for both cases, whether $y$ is divisible by $x$, or not.

Though if such a formula is complicated, then it can't be helped.

I also noted that if we take the divisible case, then the condition on the numbers would've to be changed to $z>y\ge x$.

Best Answer

If $x=1$ then you would want $z-y+1$ if $z$ and $y$ are integers; more generally you would want $\lfloor z\rfloor-\lceil y \rceil +1$. So, reintroducing $x$, try $$\bigg\lfloor\frac zx \bigg\rfloor - \bigg\lceil\frac yx \bigg\rceil +1$$

Examples:

 x   y     z          function 
                                  
 3  100   999     333 - 34 + 1 = 300
 3   99   999     333 - 33 + 1 = 301
 3  100   998     332 - 34 + 1 = 299
 3   99   998     332 - 33 + 1 = 300
 2  100   999     499 - 50 + 1 = 450
 1  100   999     999 -100 + 1 = 900

as you might hope