A positive integer is magical if it is divisible by either A or B.
Return the N-th magical number. Since the answer may be very large, return it modulo 10^9 + 7.
Example 1:
Input: N = 1, A = 2, B = 3
Output: 2
Example 2:
Input: N = 4, A = 2, B = 3
Output: 6
Example 3:
Input: N = 5, A = 2, B = 4
Output: 10
Example 4:
Input: N = 3, A = 6, B = 4
Output: 8
Note:
1 <= N <= 10^9
2 <= A <= 40000
2 <= B <= 40000
方法1:数学方法
如果
L
\color{red}{L}
L是A和B的最小公倍数
则存在不大于L的Magical数的数量是
M
=
L
/
A
+
L
/
B
−
1
\color{red}{M=L/A+L/B-1}
M=L/A+L/B−1
例如A=2,B=3,其最小公倍数L=6,则M=4
现在假设
N
=
M
∗
q
+
r
,
(
r
<
M
)
\color{red}{N=M*q+r,(r<M)}
N=M∗q+r,(r<M)
而第
M
∗
q
\color{red}{M*q}
M∗q个Magical数是
L
∗
q
\color{red}{L*q}
L∗q,接下来就是求r了,r就比较好求了
class Solution {
public int nthMagicalNumber(int N, int A, int B) {
int MOD = 1_000_000_007;
int L = A / gcd(A, B) * B;//最小公倍数
int M = L / A + L / B - 1;//小于等于最小公倍数的Magical数的数量
int q = N / M, r = N % M;//N=M*q+r
long ans = (long) q * L % MOD;
if (r == 0)
return (int) ans;
int[] heads = new int[]{A, B};
for (int i = 0; i < r - 1; ++i) {
if (heads[0] <= heads[1])
heads[0] += A;
else
heads[1] += B;
}
ans += Math.min(heads[0], heads[1]);
return (int) (ans % MOD);
}
public int gcd(int x, int y) {
if (x == 0) return y;
return gcd(y % x, x);
}
}
方法2:二分法
很明显,我们所需要求的Magical是N的单调递增函数,因此我们可以确定上边界和下边界来进行二分搜索,我们使用
f
(
x
)
\color{red}{f(x)}
f(x)来表示小于等于x的magical数的数量,则
f
(
x
)
=
f
l
o
o
r
(
x
/
A
)
+
f
l
o
o
r
(
x
/
B
)
−
f
l
o
o
r
(
x
/
L
)
\color{red}{f(x)=floor(x/A)+floor(x/B)-floor(x/L)}
f(x)=floor(x/A)+floor(x/B)−floor(x/L)(L为A,B的最小公倍数),这个公式很简单,也就是求两个集合的并集的步骤是集合A+集合B-集合AB的交集,然后就是简单的二分搜索了
class Solution {
public int nthMagicalNumber(int N, int A, int B) {
int MOD = 1_000_000_007;
int L = A / gcd(A, B) * B;
long lo = 0;
long hi = (long) 1e15;
while (lo < hi) {
long mi = lo + (hi - lo) / 2;
// If there are not enough magic numbers below mi...
if (mi / A + mi / B - mi / L < N)
lo = mi + 1;
else
hi = mi;
}
return (int) (lo % MOD);
}
public int gcd(int x, int y) {
if (x == 0) return y;
return gcd(y % x, x);
}
}