How to find number of integers not divisible by 2 nor 3 in a range?

The formula

$$f(a,b)=\left(b-\left\lfloor b\over2\right\rfloor-\left\lfloor b\over3\right\rfloor+\left\lfloor b\over6\right\rfloor \right) -\left((a-1)-\left\lfloor a-1\over2\right\rfloor-\left\lfloor a-1\over3\right\rfloor+\left\lfloor a-1\over6\right\rfloor \right)$$

will do the trick: The first piece counts the number of positive integers up to (and including) $b$ not divisible by $2$ or $3$; the second piece subtracts those that are. (strictly) less than $a$.

As someone noted in a now-deleted comment, there can be no formula for $f$ that is purely a function of $b-a$, since, for example, $f(22,31)\not=f(21,30)$ even though $31-22=30-21$.

Added later: Here's another, arguably simpler formula.

$$f(a,b)=\left(\left\lceil b\over6\right\rceil+\left\lfloor b+1\over6\right\rfloor\right)-\left(\left\lfloor a\over6\right\rfloor+\left\lceil a-1\over6\right\rceil\right)$$

Where the floor function $\lfloor x\rfloor$ rounds down to the nearest integer and the ceiling function $\lceil x\rceil$ rounds up. The idea is to round $a$ down to the nearest multiple of $6$ and $b$ up to the nearest multiple of $6$, say $A=6\lfloor a/6\rfloor$ and $B=6\rceil b/6\rceil$. There are $2(B-A)/6=2(\lceil b/6\rceil-\lfloor a/6\rfloor)$ numbers between $A$ and $B$ not divisible by $2$ or $3$. But this includes $A+1$ and $B-1$, which shouldn't be counted if $A+1\lt a$ and/or $B-1\gt b$, so it's necessary to subtract $\lceil(a-A-1)/6\rceil$ and $\lceil(B-1-b)/6\rceil$. When you simplify the expression

$$2\left(\left\lceil b\over6\right\rceil-\left\lfloor a\over6\right\rfloor\right)-\left(\left\lceil{a-1\over6}-\left\lfloor a\over6\right\rfloor \right\rceil+\left\lceil\left\lceil b\over6\right\rceil-{b+1\over6} \right\rceil \right)$$

using the fact that integer quantities move additively outside the ceiling function and $-\lceil-x\rceil=\lfloor x\rfloor$, you get the given formula.


When $b-a \gt 0$ and $6 \mid (b-a+1)$ you can use this equation,

$\quad f(a,b)=b-a + 1 -\bigg\lfloor\frac{b-a+1}{2}\bigg\rfloor-\bigg\lfloor\frac{b-a+1}{3}\bigg\rfloor+\bigg\lfloor\frac{b-a+1}{6}\bigg\rfloor$

Note that $f(20,30) = 4$, which is incorrect.