The closest divisors of a number are the pair of factors whose product is the number and whose difference is minimized. For a given number, the closest pair will be found near its square root.
classSolution {
public: vector<int> closestDivisors(int num) {
auto get = [](int n) {
for (int i = sqrt(n); i >=1; --i) {
if (n % i ==0) return vector<int>{i, n / i};
}
return vector<int>{1, n};
};
auto a = get(num +1), b = get(num +2);
returnabs(a[0] - a[1]) <= abs(b[0] - b[1]) ? a : b;
}
};
classSolution {
publicint[]closestDivisors(int num) {
int[] a = get(num + 1), b = get(num + 2);
return Math.abs(a[0]- a[1]) <= Math.abs(b[0]- b[1]) ? a : b;
}
privateint[]get(int n) {
for (int i = (int)Math.sqrt(n); i >= 1; --i) {
if (n % i == 0) returnnewint[]{i, n / i};
}
returnnewint[]{1, n};
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funclosestDivisors(num: Int): IntArray {
funget(n: Int): IntArray {
for (i inMath.sqrt(n.toDouble()).toInt() downTo 1) {
if (n % i ==0) return intArrayOf(i, n / i)
}
return intArrayOf(1, n)
}
val a = get(num + 1)
val b = get(num + 2)
returnif (kotlin.math.abs(a[0] - a[1]) <= kotlin.math.abs(b[0] - b[1])) a else b
}
}
1
2
3
4
5
6
7
8
9
10
classSolution:
defclosestDivisors(self, num: int) -> list[int]:
defget(n: int) -> list[int]:
for i in range(int(n **0.5), 0, -1):
if n % i ==0:
return [i, n // i]
return [1, n]
a = get(num +1)
b = get(num +2)
return a if abs(a[0] - a[1]) <= abs(b[0] - b[1]) else b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
impl Solution {
pubfnclosest_divisors(num: i32) -> Vec<i32> {
fnget(n: i32) -> Vec<i32> {
letmut i = (n asf64).sqrt() asi32;
while i >0 {
if n % i ==0 {
returnvec![i, n / i];
}
i -=1;
}
vec![1, n]
}
let a = get(num +1);
let b = get(num +2);
if (a[0] - a[1]).abs() <= (b[0] - b[1]).abs() { a } else { b }
}
}