medium +25 pts

Nth Magical Number

Find the nth positive integer divisible by a or b using binary search.

A positive integer is called *magical* if it is divisible by either `a` or `b`. Given three integers `n`, `a`, and `b`, return the `n`th magical number. Since the answer can be large, return it modulo `10**9 + 7`. Implement the function: ```python def nth_magical_number(n: int, a: int, b: int) -> int: ``` **Details:** - Numbers are counted starting from 1. For example, if `a=2` and `b=3`, the magical numbers are 2,3,4,6,8,9,10,12,... (not 1 because it is not divisible by 2 or 3). - Use binary search on the answer. The count of magical numbers ≤ X is `X // a + X // b - X // lcm(a, b)`. - Return the answer modulo `10**9 + 7`. **Input constraints:** - `1 ≤ n ≤ 10**9` - `1 ≤ a, b ≤ 4 * 10**4` Your solution must run in `O(log(max_value))` time, where `max_value` is the upper bound used in binary search (e.g., `max(a, b) * n`).

Constraints

1 ≤ n ≤ 10^9, 1 ≤ a, b ≤ 4*10^4. The answer may exceed 32-bit, so return modulo 1,000,000,007.

Example

```python
>>> nth_magical_number(1, 2, 3)
2
>>> nth_magical_number(4, 2, 3)
6
>>> nth_magical_number(5, 2, 4)
10
>>> nth_magical_number(3, 6, 4)
8
```
25 points ~25 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

The count of magical numbers up to X is floor(X/a) + floor(X/b) - floor(X/lcm(a,b)).
Binary search for the smallest X such that count(X) >= n.
If a and b share common factors, the lcm is smaller than a*b; use math.gcd to compute it.
After finding the exact X, return X % (10**9 + 7).
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.