题解:二分 + gcd
- 1~n中,能被a整除的个数 n/a , 能被b整除的个数 n/b, 能被a 且 b 整除的个数 n/ gcd(a,b) 则 1~n中能被a或b整除的个数为 n/a + n/b - n/gcd(a,b)
- 从1~n中二分,搜这个数k 1~k中 k/a + k/b - k/gcd(a,b) = n,也就是答案
- 因为n的范围1e9, a的范围4e4,所以最大的n为 4e13
class Solution {
public int nthMagicalNumber(int n, int a, int b) {
final int mod = (int) (1e9 + 7);
long l = 1, r = (long) 4e13;
while (l < r) {
long mid = (l + r) / 2;
if (get(mid, a, b) >= n) r = mid;
else l = mid + 1;
}
return (int) (r % mod);
}
int gcd(int a, int b) {
return b > 0 ? gcd(b, a % b) : a;
}
long get(long mid, int a, int b) {
return mid / a + mid / b - mid / ((long) a * b / gcd(a, b));
}
}
标签:gcd,878,int,mid,long,整除,神奇,数字
From: https://www.cnblogs.com/eiffelzero/p/16916143.html