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 109 + 7.
Example 1:
Input: n = 1, a = 2, b = 3
Output: 2
Example 2:
Input: n = 4, a = 2, b = 3
Output: 6
Constraints:
1 <= n <= 109
2 <= a, b <= 4 * 104
Solutions
Solution 1
Thinking
The \(n\)-th positive integer divisible by \(a\) or \(b\), with \(n\) up to \(10^9\). Listing multiples is too slow. The count of magical numbers \(\le x\) is \(x/a+x/b-x/\mathrm{lcm}(a,b)\), monotone in \(x\).
Binary-search the least \(x\) whose count is \(n\), then reduce modulo \(10^9+7\). The bound \((a+b)\cdot n\) is sufficient.