The n-th Exclusive Multiple in O(1)
Given two coprime numbers, jump straight to the n-th integer divisible by exactly one of them, with no search and no loop over candidates: just a handful of arithmetic operations.
The problem
Fix two coprime integers $a, b > 1$ with $a < b$, and a positive integer $n$. Find the $n$-th smallest positive integer that is divisible by $a$ or by $b$, but not both.
For $a=2, b=3$ the qualifying integers start $2, 3, 4, 8, 9, 10, 14, 15, 16, \dots$ ($6$ and $12$ are skipped, since they are multiples of both).
The O(1) formula
The qualifying integers are periodic with period $ab$, with exactly $S = a+b-2$ of them per period. Peel off the whole periods that sit below the answer, then place the leftover rank inside the final window in closed form:
Closed form
$$ \begin{aligned} S &= a+b-2, \qquad r = n \bmod S, \qquad \text{filler} = \left\lfloor \tfrac{n}{S} \right\rfloor ab, \\[6pt] i &= \left\lfloor \frac{r\,b}{a+b} \right\rfloor, \qquad\quad j = \left\lfloor \frac{r\,a}{a+b} \right\rfloor, \\[6pt] E(n) &= \text{filler} \,+\, \min\!\big(a\,(i{+}1),\; b\,(j{+}1)\big). \end{aligned} $$Two edge cases fold in cleanly: if $n\,a < b$ the first $n$ multiples of $a$ all precede $b$, so the answer is simply $n\,a$; and if $r = 0$ the answer lands exactly on a window boundary, at $\text{filler} - a$. Everything here is $O(1)$: independent of $n$ and of the magnitudes of $a$ and $b$.
The code
// n is 1-indexed; a < b, gcd(a,b) = 1, a > 1
long trUE_n_Smallest_AB(long a, long b, long n) {
if (n * a < b) return n * a;
if (n * a == b) return a * (n + 1); // defensive; unreachable given a>1, gcd(a,b)=1
long filler = 0, sum = 0;
if (n > a + b - 2) {
sum = a + b - 2;
filler = (n / sum) * a * b;
n %= sum;
}
if (n == 0) return filler - a; // landed exactly on a window boundary
long rat_a = (n * b) / (a + b); // estimated multiples of a consumed
long rat_b = (n * a) / (a + b); // estimated multiples of b consumed
if (a * rat_a > b * rat_b)
return Math.min(a * rat_a + a, b * rat_b + b) + filler;
else
return a * rat_a + a + filler;
}
Related problems
The union cousins of this problem, "divisible by at least one," are two common interview questions:
- Nth Magical Number (the $n$-th integer divisible by $a$ or $b$).
- Ugly Number III (divisible by $a$, $b$, or $c$).