Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

878. Nth Magical Number

MathBinary Search

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.

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);
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.