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
Find 4th Magical Number (a=2, b=3)A number is magical if divisible by 2 OR 312345678not magical÷2 ✓ (1st)÷3 ✓ (2nd)÷2 ✓ (3rd)not magical÷2,÷3 ✓ (4th)not magical÷2 ✓ (5th)Counting Formula (Inclusion-Exclusion)Count(x) = floor(x/2) + floor(x/3) - floor(x/6)Answer: 6 (4th magical number)Optimal: Binary search + mathematical counting in O(log n) time
Understanding the Visualization
1
Input
n=4, a=2, b=3 - find 4th magical number
2
Process
Numbers divisible by 2 OR 3: 2,3,4,6,8,9,10,12...
3
Output
4th magical number is 6
Key Takeaway
🎯 Key Insight: Use binary search on answer space with inclusion-exclusion principle to count magical numbers efficiently
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