Nth Magical Number - Problem

A positive integer is magical if it is divisible by either a or b.

Given the three integers n, a, and b, return the n-th magical number. Since the answer may be very large, return it modulo 109 + 7.

Input & Output

Example 1 — Basic Case
$ Input: n = 1, a = 2, b = 3
Output: 2
💡 Note: The first magical number is 2, since 2 % 2 == 0
Example 2 — Multiple Numbers
$ Input: n = 4, a = 2, b = 3
Output: 6
💡 Note: Magical numbers are 2, 3, 4, 6. The 4th is 6 (divisible by both 2 and 3)
Example 3 — Larger Case
$ Input: n = 3, a = 6, b = 4
Output: 8
💡 Note: Magical numbers are 4, 6, 8. The 3rd magical number is 8

Constraints

  • 1 ≤ n ≤ 109
  • 2 ≤ a, b ≤ 4 × 104

Visualization

Tap to expand
Nth Magical Number - Optimal Solution INPUT Find nth number divisible by a OR b 1 2 3 4 5 6 Divisible by a=2 Divisible by b=3 Divisible by both (LCM) n 1 a 2 b 3 Magical: divisible by 2 OR 3 Sequence: 2, 3, 4, 6, 8, 9... LCM(2,3) = 6 ALGORITHM STEPS 1 Binary Search Setup lo=1, hi=n*min(a,b) 2 Count Function count(x) = x/a + x/b - x/lcm For x=2: 2/2 + 2/3 - 2/6 = 1+0-0 = 1 count(2) = 1 (OK for n=1) 3 Binary Search Find smallest x: count(x)>=n mid = (lo + hi) / 2 if count(mid) >= n: hi = mid else: lo = mid+1 4 Return Result return lo % (10^9 + 7) Time: O(log(n*min(a,b))) FINAL RESULT The 1st magical number is: 2 Verification: [OK] 2 % 2 = 0 (divisible) [X] 2 % 3 = 2 (not div) [OK] 2 is magical! Magical sequence starts: 2 3 4 6 ... Key Insight: Use Binary Search + Inclusion-Exclusion principle. For any number x, we can count magical numbers up to x as: count(x) = floor(x/a) + floor(x/b) - floor(x/LCM(a,b)). This avoids double-counting numbers divisible by both a and b. Binary search finds the smallest x where count(x) >= n. TutorialsPoint - Nth Magical Number | Binary Search + Inclusion-Exclusion
Asked in
Google 15 Facebook 12 Amazon 8
28.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen