Skip to content

Commit 9552019

Browse files
committed
Create 1360.最接近的因数.js
1 parent 7987873 commit 9552019

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

1360.最接近的因数.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* @param {number} num
3+
* @return {number[]}
4+
*/
5+
var closestDivisors = function(num) {
6+
function getNear(n) {
7+
const t = Math.floor(Math.sqrt(n));
8+
9+
if (n % t === 0) {
10+
return [t, n / t];
11+
}
12+
13+
let upper = 0;
14+
if (Math.abs(num - t * t) < Math.abs(num - (t + 1) * (t + 1))) {
15+
upper = t;
16+
} else {
17+
upper = t + 1;
18+
}
19+
while (upper) {
20+
if (n % upper === 0) {
21+
return [upper, n / upper];
22+
}
23+
upper--;
24+
}
25+
}
26+
27+
const a = getNear(num + 1);
28+
const b = getNear(num + 2);
29+
30+
if (Math.abs(a[0] - a[1]) < Math.abs(b[0] - b[1])) {
31+
return a;
32+
} else {
33+
return b;
34+
}
35+
};

0 commit comments

Comments
 (0)