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 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
πŸ”­ The Magic Number TelescopeConstellation A(divisible by a)Constellation B(divisible by b)Overlap: LCM(a,b)Inclusion-Exclusion FormulaCount(x) = ⌊x/aβŒ‹ + ⌊x/bβŒ‹ - ⌊x/lcmβŒ‹Add A starsAdd B starsSubtract overlappedLMRBinary Search ProgressTelescope adjusts focus until Count(mid) = n🎯 Result: O(log n) complexity!Smart telescope finds the nth star without checking each one
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!
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
52.3K Views
Medium-High Frequency
~25 min Avg. Time
1.8K 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