# 1201. Ugly Number III
Write a program to find the n-th ugly number.
Ugly numbers are positive integers which are divisible by a or b or c.
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 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 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 5th is 10.
Example 4:
Input: n = 1000000000, a = 2, b = 217983653, c = 336916467
Output: 1999999984
Constraints:
1 <= n, a, b, c <= 10^9
1 <= a * b * c <= 10^18
It's guaranteed that the result will be in range [1, 2 * 10^9]
# Solution
Approach 1: use multiple pointers (two pointers) -- TLE.
Approach 2: binary search to find the smallest num whose num_uglies_le == n.
# Code (Python)
Approach 1:
def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int:
# multi pointers, TLE
a, b, c = sorted([a, b, c])
if n == 1:
return a
ugly_a, ugly_b, ugly_c = a, b, c
for i in range(n - 1):
# eleminate duplicates
if ugly_a == ugly_b or ugly_a == ugly_c:
ugly_a += a
elif ugly_b == ugly_c:
ugly_b += b
# advance a ugly number
if ugly_a < ugly_b and ugly_a < ugly_c:
ugly_a += a
elif ugly_b < ugly_a and ugly_b < ugly_c:
ugly_b += b
else:
ugly_c += c
return min(ugly_a, ugly_b, ugly_c)
Approach 2:
def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int:
# idea: binary search. Want to find the smallest num where the number of uglies less or equal to it is n.
a, b, c = sorted([a, b, c])
lcm_ab = self._lcm(a, b) # least common multiple
lcm_bc = self._lcm(b, c)
lcm_ac = self._lcm(a, c)
lcm_abc = self._lcm(lcm_ab, c)
def num_uglies_le(number): # less OR EQUAL
# by inclusion-exclusion principle
return number // a + number // b + number // c - number // lcm_ab - number // lcm_bc - number // lcm_ac + number // lcm_abc
# binary search to find the smallest num whose num_uglies_le == n
low, high = a, 2e9
while low < high: # ends with low == high, try 2 or 3 elements
mid = (low + high) // 2
if num_uglies_le(mid) < n:
low = mid + 1
else: # >= n, meaning mid could be the smallest == n (if equal to n)
high = mid
return int(high)
# algorithm to calculate the least common multiple
def _lcm(self, x, y):
return x * y // self._gcd(x, y)
# algorithm to calculate the greatest common divisor
def _gcd(self, x, y):
if x == 0:
return y
return self._gcd(y % x, x)
# Code (C++)
Approach 1:
Approach 2: