1362. Closest Divisors
https://leetcode.com/problems/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.
Example 1:
Input: num = 8
Output: [3,3]
Explanation: For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen.
Example 2:
Input: num = 123
Output: [5,25]
Example 3:
Input: num = 999
Output: [40,25]
Constraints:
1 <= num <= 10^9
对给定的整数num,找两个最近的整数使得它们的积等于num + 1或num + 2。当num + 1或2有平方根时,最近的两个数是平方根。因此从平方根开始往下遍历,遇到的第一个能被整除的就是结果。又因为num+1比+2小,当除数为1时返回num + 1能得到差的绝对值更小的。
class Solution {
public:
vector<int> closestDivisors(int num) {
for (int i = sqrt(num + 2); i >= 1; --i) {
if ((num + 1) % i == 0) return {(num + 1) / i, i};
if ((num + 2) % i == 0) return {(num + 2) / i, i};
};
return {};
}
};
Last updated
Was this helpful?