#1362
Medium Algorithms Closest divisors
Math
62.0% acceptance
Feb 25, 2026
339
101
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.
Solution
Rust
Time O(2^n)
Space O(n)
impl Solution {
pub fn closest_divisors(num: i32) -> Vec<i32> {
fn best_pair(n: i32) -> (i32, i32) {
let mut i = (n as f64).sqrt() as i32;
while i >= 1 {
if n % i == 0 { return (i, n / i); }
i -= 1;
}
(1, n)
}
let (a1, b1) = best_pair(num + 1);
let (a2, b2) = best_pair(num + 2);
if b1 - a1 <= b2 - a2 { vec![a1, b1] } else { vec![a2, b2] }
}
}