<p>A positive integer is <em>magical</em> if it is divisible by either <code>a</code> or <code>b</code>.</p>

<p>Given the three integers <code>n</code>, <code>a</code>, and <code>b</code>, return the <code>n<sup>th</sup></code> magical number. Since the answer may be very large, <strong>return it modulo </strong><code>10<sup>9</sup> + 7</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> n = 1, a = 2, b = 3
<strong>Output:</strong> 2
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> n = 4, a = 2, b = 3
<strong>Output:</strong> 6
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li>
	<li><code>2 &lt;= a, b &lt;= 4 * 10<sup>4</sup></code></li>
</ul>

class Solution:
    def nthMagicalNumber(self, n: int, a: int, b: int) -> int:
        # calculate great common divisor
        def gcd(a, b):
            return a if b == 0 else gcd(b, a % b)

        # count the number of magical number from 1~n
        def count(n):
            lcm = a / gcd(a, b) * b
            return n //a + n // b - n // lcm
        
        # binary search
        res = 0
        l, r = 1, min(a, b) * n
        while l <= r:
            m = l + (r - l) // 2
            if count(m) < n:
                l = m + 1
            else:
                res = m
                r = m - 1
        return res % ( 10 ** 9 + 7)
16500