-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathsolution1.js
45 lines (40 loc) · 836 Bytes
/
solution1.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* https://leetcode-cn.com/problems/closest-divisors/
*
* 5171. 最接近的因数
*
* Medium
*
* 108ms 100.00%
* 34.7mb 100.00%
*/
const closestDivisors = num => {
const [x1, y1] = findTwoNumber(num + 1);
const [x2, y2] = findTwoNumber(num + 2);
const abs1 = Math.abs(x1 - y1);
const abs2 = Math.abs(x2 - y2);
if (abs1 < abs2) {
return [x1, y1];
} else {
return [x2, y2];
}
}
function findTwoNumber(num) {
let mid = Math.floor(Math.sqrt(num));
let x = 0;
let y = 0;
let distance = Number.MAX_SAFE_INTEGER;
while (mid > 0) {
const other = num / mid;
if (other % 1 === 0) {
const tempDistance = Math.abs(mid - other);
if (tempDistance < distance) {
x = mid;
y = other;
distance = tempDistance;
}
}
mid--;
}
return [x, y];
}