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;
}
相关推荐
zyl7659 小时前
FlashAttention 详解:从 GPU 硬件、普通 Attention 到分块计算与 Online Softmax
算法
爱读书的小胖13 小时前
LeetCode 122:买卖股票的最佳时机 II(C)解题分析
算法
结局无敌13 小时前
React Native for OpenHarmony 实战:三方库 react-native-modal-dialog 的鸿蒙化适配指南
深度学习·算法·react native·react.js·harmonyos
OPEN-F13 小时前
ROS2系列教程:上位机建图与导航(原理综合)
算法·机器人
weixin_3077791313 小时前
C++代码实现MATLAB中的fitrtree函数功能
开发语言·c++·算法·matlab
爱读书的小胖14 小时前
Codewars:Rot13(C)解题分析
c语言·开发语言
tomwang032214 小时前
路径优化建模、优化算法分类及工程化小结
算法·数学建模·分类
小羊没烦恼!14 小时前
Ajax与JSON的一些总结
android·java·前端·数据库·mysql·算法·okhttp
2501_9269783314 小时前
人机通信协议--人和机器之间的交互想象
人工智能·经验分享·算法·ai写作
行者全栈架构师14 小时前
【鸿蒙心迹】互动卡片全链路——把核心功能放到桌面(FormKit 实战)(HarmonyOS 7.x)
前端·算法·架构