leetcode **878. Nth magic number (2022.11.22)

[Title] **878. The Nth magic number

A positive integer is magical if it is divisible by either a or b.
Given three integers n , a , b , return the nth magic number. Since the answer may be large, return the answer modulo 109 + 7.

Example 1:

输入:n = 1, a = 2, b = 3
输出:2
示例 2:

输入:n = 4, a = 2, b = 3
输出:6

hint:

1 <= n <= 109
2 <= a, b <= 4 * 104

[Problem-solving ideas 1] Dichotomy

At first I thought it was similar to an ugly number, but later I found out that there are only two factors of a and b = =
direct violence, timeout, I did not expect to search directly from Min(a, b) to Min(a n, b
n) The number of magic numbers before max = the number of multiples of a + the number of multiples of b - the number of common multiples of a and b Before M, the number of multiples of x = m divided by x and rounded
down

class Solution {
    
    
    public int nthMagicalNumber(int n, int a, int b) {
    
    
        if(a % b == 0)return nthMagicalNumber(n, b);
        if(b % a == 0)return nthMagicalNumber(n, a);

        long ret = -1;
        long l = 1, r = (long)n * Math.min(a, b);
        //求a和b的最公倍数p
        int p = a, i = 1;
        while(p * i % b != 0)i++;
        p = p * i;

        //二分查找,直到某个数之前恰好有n个神奇数字。
        while(l <= r){
    
    
            long m = l + (r - l)/2;
            // 求m之前的神奇数字的个数:a的倍数的数量,加上b的倍数的数量,再减去a和b的公倍数的数量
            if( m / a + m / b - m / p >= n)r = --m;
            else l = ++m;
        }
        
        return (int)(l%1000000007);
    }

    public int nthMagicalNumber(int n, int a) {
    
    
        return (int)((long)n * a % 1000000007);
    }
}

Guess you like

Origin blog.csdn.net/XunCiy/article/details/127975163