Skip to content

Commit ba3f515

Browse files
committed
feat: 1201. Ugly Number III.js : 二分 + 数论
1 parent 6e95916 commit ba3f515

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* @param {number} n
3+
* @param {number} a
4+
* @param {number} b
5+
* @param {number} c
6+
* @return {number}
7+
*/
8+
const gcd = (a, b) => b ? gcd(b, a % b) : a
9+
const lcm = (a, b) => a * b / gcd(a, b)
10+
const nthUglyNumber = function (n, a, b, c) {
11+
const min = BigInt(Math.min(a, b, c))
12+
n = BigInt(n), a = BigInt(a), b = BigInt(b), c = BigInt(c)
13+
let l = 1n; let r = n * min
14+
while (l < r) {
15+
const mid = l + r >> 1n
16+
if (valid(mid)) r = mid
17+
else l = mid + 1n
18+
}
19+
function valid (m) {
20+
const cnt = (d) => m / d
21+
return (cnt(a) + cnt(b) + cnt(c) - cnt(lcm(a, b)) - cnt(lcm(b, c)) - cnt(lcm(a, c)) + cnt(lcm(lcm(a, b), c))) >= n
22+
}
23+
return l
24+
}

leetcode/残酷刷题/README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,8 @@
141141
- 1751. Maximum Number of Events That Can Be Attended II
142142
- 1300. Sum of Mutated Array Closest to Target
143143
- 1802. Maximum Value at a Given Index in a Bounded Array
144+
- 1201. Ugly Number III.js
145+
- 二分 + 容斥原理 + lcm
144146

145147
### 并查集
146148

0 commit comments

Comments
 (0)