> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Nth Magical Number Python Solution with Tests

> Tested Python solution for LeetCode 878 with 18 pytest cases. Generate a practice environment with lcpy.

LeetCode 878, [Hard](/catalog/hard). Topics: [Math](/catalog/topics/math), [Binary Search](/catalog/topics/binary-search), [Number Theory](/catalog/topics/number-theory). [View on LeetCode](https://leetcode.com/problems/nth-magical-number/description/).

Generate this problem as a practice environment: tested reference solution, 18 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 878   # by problem number
lcpy gen -s nth_magical_number   # by problem name
```

## 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 nth magical number. Since the answer may be very large, return it modulo `10^9 + 7`.

### Examples

```
Input: n = 1, a = 2, b = 3
Output: 2
```

```
Input: n = 4, a = 2, b = 3
Output: 6
```

### Constraints

* 1 \<= n \<= 10^9
* 2 \<= a, b \<= 4 \* 10^4

**Follow up:** Could you solve the problem in `O(log(n * min(a, b)))` time complexity?

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/nth_magical_number/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/nth_magical_number/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from math import gcd


class Solution:
    # Time: O(log(n * min(a, b)))
    # Space: O(1)
    def nth_magical_number(self, n: int, a: int, b: int) -> int:
        mod = 10**9 + 7
        lcm = a * b // gcd(a, b)

        def count(x: int) -> int:
            return x // a + x // b - x // lcm

        low, high = 1, n * min(a, b)
        while low < high:
            mid = (low + high) // 2
            if count(mid) >= n:
                high = mid
            else:
                low = mid + 1
        return low % mod
```

## Complexity

| Time | Space |
| - | - |
| O(log(n \* min(a, b))) | O(1) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.