leetcode 878.Nth Magical Number

class Solution {
public:

const double kRrmainder = 1000000007;

int GetGcd(int a, int b) {
    int t = 0;
    while (b) {
        t = b;
        b = a % b;
        a = t;
    }
    return a;
}

int GetLcm(int a, int b){
    return a / GetGcd(a, b) * b;
}

template<class T>
T vanxkr_max(const T &a, const T &b) {
    return a > b ? a : b;
}

template<class T>
T vanxkr_min(const T &a, const T &b) {
    return a < b ? a : b;
}

int nthMagicalNumber(int N, int A, int B) {
    double max = vanxkr_max(A, B);
    double min = vanxkr_min(A, B);
    if (1 == N) {
        return static_cast<int>(fmod(min,kRrmainder));
    }
    if (A == B){
        return static_cast<int>(fmod(static_cast<double>(A)*static_cast<double>(N), kRrmainder));
    }

    if (0 == static_cast<int>(fmod(max,min))) {
        return static_cast<int>(fmod(static_cast<double>(N)* min, kRrmainder));
    } else {
        double lcm = static_cast<double>(GetLcm(static_cast<int>(min), static_cast<int>(max)));
        double num = N;
        double minValue;
        int delt;
        int tempDelt;
        double ret;
        int change;
        while (true) {
            minValue = num * min;
            delt = (int)(minValue / max);
            tempDelt = (int)(minValue / lcm);
            if ((num + delt - tempDelt) > N + 1){
                num -= (int)((num + delt - tempDelt - N) / 2);
                continue;
            }
            change = (int)num + delt - tempDelt - N;
            if (change > 0) {
                if (delt * max > num *min) {
                    ret = vanxkr_max((delt - change) * max, num * min);
                } else if (delt * max == num * min) {
                    ret = vanxkr_max((delt - change) * max, (num - change) * min);
                } else {
                    ret = vanxkr_max(delt * max, (num - change) * min);
                }
            } else {
                ret = vanxkr_max(delt * max, num * min);
            }
            return static_cast<int>(fmod(ret, kRrmainder));
        }
    }
}
};

本文作者:vanxkr

本文链接:http://www.vanxkr.com/2019/5/leetcode.878.Nth Magical Number

版权声明:本博客所有文章除特别声明外,均采用CC BY-NC-SA 3.0许可协议。转载请注明出处!

最大公约数GCD和最小公倍数LCM
0 条评论
已登录,注销 取消