【leetcode】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
.
Example 1:
Input: n = 1, a = 2, b = 3
Output: 2
Example 2:
Input: n = 4, a = 2, b = 3
Output: 6
暴力法:用set接收数据,然后两个数字依次累加,超时了。
class Solution {
public:
int nthMagicalNumber(int n, int a, int b) {
// 用set去重
long M=10e9+7;
set<long>dp;
long tmpa=a,tmpb=b;
while(dp.size()<n){
if(tmpa<tmpb){
dp.insert(tmpa);
tmpa=(tmpa+a)%M;
}
else if(tmpa>tmpb){
dp.insert(tmpb);
tmpb=(tmpb+b)%M;
}
else{
dp.insert(tmpa);
tmpa=(tmpa+a)%M;
tmpb=(tmpb+b)%M;
}
}
auto zz=--dp.end();
return *(zz);
}
};
用二分法来求解,参考了大佬的帖子。
class Solution {
public:
int nthMagicalNumber(int N, int A, int B) {
long lcm = A * B / gcd(A, B), left = 2, right = 1e14, M = 1e9 + 7;
while (left < right) {
long mid = left + (right - left) / 2;
if (mid / A + mid / B - mid / lcm < N) left = mid + 1;
else right = mid;
}
return right % M;
}
int gcd(int a, int b) {
return (b == 0) ? a : gcd(b, a % b);
}
};