Skip to content

Latest commit

 

History

History
72 lines (59 loc) · 1.49 KB

README_CN.md

File metadata and controls

72 lines (59 loc) · 1.49 KB

1362. 最接近的因数

给你一个整数 num,请你找出同时满足下面全部要求的两个整数:

  • 两数乘积等于 num + 1num + 2
  • 以绝对差进行度量,两数大小最接近

你可以按任意顺序返回这两个整数。

示例 1:

输入: num = 8
输出: [3,3]
解释: 对于 num + 1 = 9,最接近的两个因数是 3 & 3;对于 num + 2 = 10, 最接近的两个因数是 2 & 5,因此返回 3 & 3 。

示例 2:

输入: num = 123
输出: [5,25]

示例 3:

输入: num = 999
输出: [40,25]

提示:

  • 1 <= num <= 10^9

题解 (Ruby)

1. 题解

# @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

题解 (Rust)

1. 题解

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
    }
}