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
最优解当然是 n² = num + 1 或者 n² = num + 1, 因为 1 <= num <= 1000000000, 那我们的 n 自然不会大于 40000, 有了这个条件托底, 我们就算用最简单的方法从 40000 一路试到 1 也可以, 当然, 最好是把 n 先判断出来
impl Solution {
pub fn closest_divisors(num: i32) -> Vec<i32> {
if num == 1 {
return vec![1, 2];
}
let num = num as i64;
// 指数
let mut e = 1u32;
loop {
if 2i64.pow(e) >= num {
break;
}
e += 1;
}
// 计算出n的上限
let n = 2i64.pow(e / 2 + e % 2);
let mut a = i64::MAX;
let mut b = 0;
for v in (1..=n).rev() {
if (num + 1) % v == 0 {
if ((num + 1) / v - v).abs() < (a - b).abs() {
a = (num + 1) / v;
b = v;
}
}
if (num + 2) % v == 0 {
if ((num + 2) / v - v).abs() < (a - b).abs() {
a = (num + 2) / v;
b = v;
}
}
}
vec![a as i32, b as i32]
}
}