LeetCode 878: Nth Magical Number Solution

Master LeetCode problem 878 (Nth Magical Number), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

878. Nth Magical Number

Problem Explanation

Explanation

To solve this problem, we can use the concept of binary search. We can find the least common multiple (LCM) of a and b and then use binary search to find the nth magical number within a range of [1, n * min(a, b)]. We can calculate the LCM using the formula LCM(a, b) = a * b / GCD(a, b) where GCD is the greatest common divisor. Once we have the LCM, we can find how many magical numbers are there in each interval of length LCM. Using binary search, we can efficiently find the nth magical number.

Solution Code

class Solution {
    public int nthMagicalNumber(int n, int a, int b) {
        long mod = 1000000007;
        long lcm = a / gcd(a, b) * b;
        long low = 1, high = (long)1e18;
        
        while (low < high) {
            long mid = low + (high - low) / 2;
            long count = mid / a + mid / b - mid / lcm;
            
            if (count < n) {
                low = mid + 1;
            } else {
                high = mid;
            }
        }
        
        return (int)(low % mod);
    }
    
    private long gcd(long a, long b) {
        if (b == 0) return a;
        return gcd(b, a % b);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 878 (Nth Magical Number)?

This page provides optimized solutions for LeetCode problem 878 (Nth Magical Number) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 878 (Nth Magical Number)?

The time complexity for LeetCode 878 (Nth Magical Number) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 878 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 878 in Java, C++, or Python.

Back to LeetCode Solutions