深入解析:LeetCode //C - 878. 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 modulo1
 
 
 
 0
 
 
 9
 
 
 
 +
 
 
 7
 
 
 
 10^9 + 7109+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 < = 1 0 9 1 <= n <= 10^91<=n<=109
 - 2 < = a , b < = 4 ∗ 1 0 4 2 <= a, b <= 4 * 10^42<=a,b<=4∗104
 
From: LeetCode
 Link: 878. Nth Magical Number
Solution:
Ideas:
Definition: A magical number is divisible by either a or b.
Goal: Find the n-th magical number.
Key math:
Count of magical numbers ≤ x = x/a + x/b - x/lcm(a, b).
Use gcd to compute lcm.
Approach:
Binary search the smallest number x such that count ≥ n.
Search range: [1, min(a, b) * n].
Result: Return x % (10^9 + 7).
Code:
int nthMagicalNumber(int n, int a, int b) {
const long long MOD = 1000000007LL;
// gcd
long long x = a, y = b;
while (y) { long long t = x % y; x = y; y = t; }
long long g = x;
long long lcm = (long long)a / g * b;
long long lo = 1;
long long minab = a < b ? a : b;
long long hi = minab * (long long)n; // upper bound
while (lo < hi) {
long long mid = lo + (hi - lo) / 2;
long long cnt = mid / a + mid / b - mid / lcm; // numbers divisible by a or b
if (cnt >= n) hi = mid;
else lo = mid + 1;
}
return (int)(lo % MOD);
}
                    
                
                
            
        
浙公网安备 33010602011771号