[LeetCode] Closest Divisors

1362. Closest Divisors

Given an integer num, find the closest two integers in absolute difference whose product equals num + 1 or num + 2.

Return the two integers in any order.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
vector<int> helper(int n) {
int s = sqrt(n);
while(s) {
if(n % s == 0) return {s, n/s};
s--;
}
return {};
}
public:
vector<int> closestDivisors(int num) {
vector<int> A = helper(num + 1), B = helper(num + 2);
return abs(A[0] - A[1]) < abs(B[0] - B[1]) ? A : B;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/27/PS/LeetCode/closest-divisors/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.