LeetCode //C - 1201. Ugly Number III

1201. Ugly Number III

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 t h n^{th} nth 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 r d 3^{rd} 3rd 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 t h 4^{th} 4th 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 t h 5^{th} 5th is 10.

Constraints:
  • 1 < = n , a , b , c < = 10 9 1 <= n, a, b, c <= 10^9 1<=n,a,b,c<=109
  • 1 < = a ∗ b ∗ c < = 10 18 1 <= a * b * c <= 10^{18} 1<=a∗b∗c<=1018
  • It is guaranteed that the result will be in range 1 , 2 ∗ 10 9 1, 2 \* 10\^9 1,2∗109.

From: LeetCode

Link: 1201. Ugly Number III


Solution:

Ideas:

binary search the answer.

For a number x, count how many numbers <= x are divisible by a, b, or c using inclusion-exclusion.

Code:
c 复制代码
long long gcd(long long x, long long y) {
    while (y) {
        long long t = x % y;
        x = y;
        y = t;
    }
    return x;
}

long long lcm(long long x, long long y) {
    return x / gcd(x, y) * y;
}

int nthUglyNumber(int n, int a, int b, int c) {
    long long A = a, B = b, C = c;

    long long ab = lcm(A, B);
    long long ac = lcm(A, C);
    long long bc = lcm(B, C);
    long long abc = lcm(ab, C);

    long long left = 1, right = 2000000000LL;

    while (left < right) {
        long long mid = left + (right - left) / 2;

        long long count = mid / A + mid / B + mid / C
                        - mid / ab - mid / ac - mid / bc
                        + mid / abc;

        if (count >= n) {
            right = mid;
        } else {
            left = mid + 1;
        }
    }

    return (int)left;
}
相关推荐
花椒技术2 小时前
2.46 秒生成 5 秒视频:拆解 H3 Max 的模型、推理栈与硬件协同
算法·音视频开发·视频编码
vivo互联网技术2 小时前
ART:妆容迁移框架,重新定义高保真妆容迁移 | ECCV 2026
人工智能·算法·图像识别
用户0441440924492 小时前
卫星信号模拟器里的四个坐标转换公式
算法
橘和柠2 小时前
阿里 open-code-review (AI代码审查工具)实战:安装、四层规则链、自定义规则格式与实测避坑
算法·面试
得物技术2 小时前
别再只卷向量检索了,得物交易搜索如何用“生成式”实现召回范式跃迁?
人工智能·算法·llm
罗西的思考2 小时前
[Agent Memory / 强化学习] MemPO源码学习笔记 ---(4)--- Rollout实现细节
人工智能·算法
罗西的思考2 小时前
机器人 / 物理 Agent Harness 综合分析与对比:从「更强的模型」到「更好的系统」
人工智能·算法·机器学习
库玛西2 小时前
攻克 408 数据结构:图论基石深度拆解(数学极值推演 + 存储内存剖析 + BFS/DFS 双核模板)
数据结构·算法·深度优先·广度优先·图搜索算法
晓蛋5 天前
c语言指的是什么意思
c语言·编译器·编程开发·集成开发环境·程序实例
倒头就睡的小比特5 天前
算法竞赛C++常用的STL
c++·算法