878. Nth Magical Number
题目大意:问第N个能整除A或者B的数 是多少。
解题思路:能整除A或者B的数,肯定是A或者B的整数倍,所以LCM(A,B)肯定满足,那么将会出现一个循环,算出循环后暴力。
typedef long long ll;
typedef unsigned long long ull;
#define mp make_pair
const int mod = 1e9+7;
int gcd(int a,int b) { return a%b==0?b:gcd(b,a%b); }
class Solution {
public:
int nthMagicalNumber(int N, int A, int B) {
ll C = A*B/gcd(A,B);
ll step = C/A + C/B -1;
ll x = (N/step * C) %mod;
N%=step;
int ta=A,tb=B;
while(N--)
{
if(N==0)
{
if(ta<tb) return (x+ta)%mod;
return (x+tb)%mod;
}
if(ta<tb) ta+=A;
else tb+=B;
}
return x;
}
};