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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code