LeetCode Entry

1201. Ugly Number III

01.12.2026 medium 2026 kotlin rust

nth number divisible by any of a,b,c

1201. Ugly Number III medium substack youtube

https://dmitrysamoylenko.com/leetcode/

01.12.2026.webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/1559

Problem TLDR

nth number divisible by any of a,b,c

Intuition

    // doesn't look like a medium problem
    // nth 10^9 can't generate all of them
    // a*b*c 10^18

    // multipliers are a, b, c, a*a, a*b, a*c, b*b, b*c, c*c, a*a*a, a*b*b, anything
    // how fast this grows?
    // if we have anything == 1 then the other two still matters
    // if a>1, then it grows exponentially in a^x pattern at least
    // so not so many numbers?
    // all combinations i,j,k of a^i b^j c^k
    // i,j,k in 1..18

    // wrong - its *any* number divisible %, not just multipliers
    //         10%2 is ok
    // so it is much more numbers count
    // 23 minute: use hints
    // 36 minute: give up

Count of divisors in 1..x range is x/a + x/b + x/c - overcount of ab,bc,ac lcm + overcount of abc lcm. Then binary search the range X to be == n.

Approach

  • gcd mnemonic “bab”: b,a%b -> if (b==0) a else gcd(b,a%b)
  • lcm = a*b/gcd

Complexity

  • Time complexity: \(O(1)\)

  • Space complexity: \(O(1)\)

Code

    fun nthUglyNumber(n: Int, a: Int, b: Int, c: Int)=run {
        fun g(x: Long, y: Long): Long = if (y == 0L) x else g(y, x % y)
        fun l(x: Long, y: Int) = x / g(x, y + 0L) * y
        val ab = l(a + 0L, b); val ac = l(a + 0L, c); val bc = l(b + 0L, c)
        val abc = l(ab, c); var lo = 1L; var hi = 1L shl 31
        while (lo < hi) {
            val m = (lo + hi) / 2
            if (m/a+m/b+m/c-m/ab-m/ac-m/bc+m/abc<n) lo=m+1 else hi=m
        }; lo.toInt()
    }
    pub fn nth_ugly_number(n: i32, a: i32, b: i32, c: i32) -> i32 {
        fn g(x: i64, y: i64) -> i64 { if y == 0 { x } else { g(y, x % y) } }
        let l = |x, y| x / g(x, y) * y; let [a, b, c] = [a, b, c].map(i64::from);
        let (ab, ac, bc,abc) = (l(a, b), l(a, c), l(b, c),l(l(a,b),c));
        1+(0..31).fold(0, |x, i| {
            let m = x | 1 << 30 - i;
            if m/a+m/b+m/c-m/ab-m/ac-m/bc+m/abc < n as _ { m } else { x }
        }) as i32
    }

Comments