Nth Magical Number - Problem
Magical Number Finder
Imagine you're a mathematician exploring the mystical world of magical numbers! A positive integer is considered magical if it's divisible by either
Your mission: Given three integers
Example: If
Challenge: Since the answer can be astronomically large, return it modulo
Imagine you're a mathematician exploring the mystical world of magical numbers! A positive integer is considered magical if it's divisible by either
a or b (or both).Your mission: Given three integers
n, a, and b, find the nth magical number in the infinite sequence of magical numbers.Example: If
a = 2 and b = 3, the magical numbers are: 2, 3, 4, 6, 8, 9, 10, 12, 14, 15, 16, 18...Challenge: Since the answer can be astronomically large, return it modulo
109 + 7. Input & Output
example_1.py β Basic Case
$
Input:
n = 1, a = 2, b = 3
βΊ
Output:
2
π‘ Note:
The first magical number divisible by 2 or 3 is 2 itself.
example_2.py β Multiple Magicals
$
Input:
n = 4, a = 2, b = 3
βΊ
Output:
6
π‘ Note:
Magical numbers: 2(1st), 3(2nd), 4(3rd), 6(4th). The 4th magical number is 6.
example_3.py β Large Result
$
Input:
n = 1000000000, a = 40000, b = 40001
βΊ
Output:
999720007
π‘ Note:
For very large n with coprime a,b, result needs modulo operation. The answer before modulo would be huge.
Constraints
- 1 β€ n β€ 109
- 2 β€ a, b β€ 4 Γ 104
- Return result modulo 109 + 7
- Both a and b are positive integers
Visualization
Tap to expand
Understanding the Visualization
1
Set Up the Telescope
Configure binary search range from 1 to nΓmin(a,b)
2
Calculate Star Density
Use inclusion-exclusion to count magical numbers up to any point
3
Smart Navigation
Adjust telescope focus based on whether we've found enough stars
4
Pinpoint Target
Converge on the exact location of the nth magical number
Key Takeaway
π― Key Insight: By combining binary search with mathematical formulas, we can calculate exactly how many magical numbers exist up to any point without counting them individually!
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code