Description Link to heading

1201. Ugly Number III (Medium)

An ugly number is a positive integer that is divisible by a, b, or c.

Given four integers n, a, b, and c, return the nᵗʰ ugly number.

Example 1:

Input: n = 3, a = 2, b = 3, c = 5
Output: 4
Explanation: The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3ʳᵈ is 4.

Example 2:

Input: n = 4, a = 2, b = 3, c = 4
Output: 6
Explanation: The ugly numbers are 2, 3, 4, 6, 8, 9, 10, 12... The 4ᵗʰ is 6.

Example 3:

Input: n = 5, a = 2, b = 11, c = 13
Output: 10
Explanation: The ugly numbers are 2, 4, 6, 8, 10, 11, 12, 13... The 5ᵗʰ is 10.

Constraints:

  • 1 <= n, a, b, c <= 10⁹
  • 1 <= a * b * c <= 10¹⁸
  • It is guaranteed that the result will be in range [1, 2 * 10⁹].

Solution Link to heading

Binary search + inclusion-exclusion principle.

In this approach, we perform a binary search for the value of the nth ugly number, denoted as $val$. If $val$ is less than the result ($res$), then its position in the sequence must be less than $n$.

To determine its position, we apply the inclusion-exclusion principle. It’s important to note that $a, b, c$ may not be coprime, so you should use their least common multiple!

Code Link to heading

class Solution {
  public:
    bool check(int n, long a, long b, long c, long target) {
        long ab = a * b / gcd(a, b);
        long bc = b * c / gcd(b, c);
        long ac = a * c / gcd(a, c);
        long abc = ab * c / gcd(ab, c);
        return target / a + target / b + target / c - target / ab - target / bc - target / ac + target / abc < n;
    }
    int nthUglyNumber(int n, int a, int b, int c) {
        long l = 0, r = 2e10;
        while (l < r) {
            long mid = l + (r - l) / 2;
            if (check(n, a, b, c, mid)) {
                l = mid + 1;
            } else {
                r = mid;
            }
        }
        return l;
    }
};