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.
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.
Input: num = 123 Output: [5,25]
Input: num = 999 Output: [40,25]
1 <= num <= 10^9
# @param {Integer} num
# @return {Integer[]}
def closest_divisors(num)
ret = [1, num + 1]
for n in (num + 1)..(num + 2)
for i in (Integer.sqrt(n)...1).step(-1)
if n % i == 0 and n / i - i < ret[1] - ret[0]
ret = [i, n / i]
break
end
end
end
return ret
end
impl Solution {
pub fn closest_divisors(num: i32) -> Vec<i32> {
let mut ret = vec![1, num + 1];
for n in (num + 1)..(num + 3) {
for i in (2..=((n as f64).sqrt().floor() as i32)).rev() {
if n % i == 0 && n / i - i < ret[1] - ret[0] {
ret = vec![i, n / i];
break;
}
}
}
ret
}
}