Nth Magical Number

Binary search on the answer — count magical numbers ≤ x as `x/a + x/b - x/lcm(a,b)`.

Hard
Time O(log(n * max(a, b))) Space O(1)
LeetCode
4 min read
math binary-search lcm modular-arithmetic

Problem#

A magical number is divisible by a or b. Return the n-th magical number (1-indexed) modulo 10^9 + 7.

Examples#

  • n=1, a=2, b=32.
  • n=4, a=2, b=36; n=5, a=2, b=410.

Constraints#

  • 1 <= n <= 10^9, 2 <= a, b <= 4 * 10^4.

Approach#

Binary search on x: count of magical numbers <= x by inclusion-exclusion is x/a + x/b - x/lcm(a,b). Find the smallest x whose count equals n. Take mod at the end.

Solution#

Nth Magical Number
class Solution {
public:
int nthMagicalNumber(int n, int a, int b) {
long long L = (long long)a / __gcd(a, b) * b;
long long lo = 1, hi = (long long)n * min(a, b);
while (lo < hi) {
long long m = (lo + hi) / 2;
long long c = m / a + m / b - m / L;
if (c < n) lo = m + 1; else hi = m;
}
return (int)(lo % 1000000007LL);
}
};

Editorial#

Binary search on the value works because “count of magical numbers <= x” is monotonically non-decreasing. The inclusion-exclusion via lcm avoids double-counting multiples of both. The answer doesn’t take mod until the end — modular reduction would break the monotonicity needed for binary search.

Complexity#

  • Time: O(log(n * min(a, b))).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.