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;
}
相关推荐
Tisfy2 小时前
LeetCode 3090.每个字符最多出现两次的最长子字符串:二重循环 / 滑动窗口
算法·leetcode·字符串·题解·模拟·双指针·滑动窗口
-dzk-2 小时前
【技巧】LC 136.只出现一次的数字
算法·异或
小羊先生car2 小时前
F429-HAL-RS485(回环/双机实验)(2026/8/16)
c语言·单片机·嵌入式硬件·软件构建
专注仿真3 小时前
问答大模型技术方案算法实现-RAPTOR树构建算法与BEG集成使用
python·算法
zlinear数据采集卡3 小时前
数据采集卡从入门到精通(10):采样率与分辨率的核心关系——反比律、架构分布与过采样
arm开发·嵌入式硬件·算法·fpga开发·架构·开源
白狐_7985 小时前
408 数据结构|线索二叉树两题详解:先序线索化后的空链域 + 中序前驱/后继判断
c语言·数据结构·链表
GeekZHR5 小时前
C语言指针进阶补充6:动态内存管理、mem系列内存函数、复杂指针声明,一次补齐指针的“三大盲区“
java·c语言·算法·指针
Herbert_hwt5 小时前
第七章 Java深入理解枚举类型
java·开发语言·算法
.道阻且长.5 小时前
8.LeetCode算法习题讲解--滑动窗口--长度最小的子数组
算法·leetcode·职场和发展
(❁´◡`❁)Jimmy(❁´◡`❁)5 小时前
P1156 [USACO01OPEN] 垃圾陷阱
算法·动态规划