[LeetCode] Nth Magical Number

878. Nth Magical Number

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.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int nthMagicalNumber(int n, int a, int b) {
long l = 2, r = LONG_MAX, lcm = a * b /__gcd(a,b), mod = 1e9 + 7;
while(l < r) {
long m = l + (r - l) / 2;
if((m / a + m / b - m / lcm) < n) l = m + 1;
else r = m;
}
return l % mod;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/23/PS/LeetCode/nth-magical-number/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.