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;
}
相关推荐
文丑颜不良啊16 小时前
LeetCode3041~3060题目解析
java·leetcode
罗西的思考16 小时前
【轻量化复现大模型 / KIMI K3】MTP / EAGLE‑3 模块交互式演示
人工智能·深度学习·算法
文丑颜不良啊17 小时前
LeetCode3101~3120题目解析
java·leetcode
kyle~20 小时前
模型预测控制(MPC)
算法·机器人·控制·传感器
老花眼猫21 小时前
C语言绘图方法:(10)椭圆缩放旋转
c语言·经验分享·青少年编程·课程设计
牢姐与蒯1 天前
cpp算法之哈希
c++·算法·哈希算法
开开心心就好1 天前
两张表格数据对比工具,不用写函数也能查
算法·spring·智能手机·pdf·电脑·intellij-idea·音视频
电科_银尘1 天前
【大模型算法与工程 02】线性回归与逻辑回归:从损失函数到决策边界
算法·逻辑回归·线性回归
玄昌盛不会编程1 天前
LeetCode——2243. 计算字符串的数字和
java·算法·leetcode
文丑颜不良啊1 天前
LeetCode3061~3080题目解析
java·leetcode