**输入:** 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
方法一:暴力遍历因数[超出时间限制]
对于想要分解的数字,暴力遍历所有比它小的数字,尝试分解。
[]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution: defdivide(self, n): ans = [0, int(1e9)] for i inrange(1, n + 1): if n % i == 0: ifabs(n // i - i) < abs(ans[0] - ans[1]): ans = [n // i, i] return ans
defclosestDivisors(self, num: int) -> List[int]: ans = [0, int(1e9)] for i inrange(num + 1, num + 3): cur = self.divide(i) ifabs(cur[0] - cur[1]) < abs(ans[0] - ans[1]): ans = cur return ans
[]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { vector<int> ans{}; public: voiddivide(int n){ for (int i = 1; i != n + 1; ++i) if (n % i == 0) if (abs(n / i - i) < abs(ans[0] - ans[1])) { ans[0] = n / i; ans[1] = i; } } vector<int> closestDivisors(int num){ ans.push_back(0); ans.push_back(1e9); divide(num + 1); divide(num + 2); return ans; } };
classSolution: defdivide(self, n): for i inrange(int(math.sqrt(n)), 0, -1): if n % i == 0: return [i, n // i]
defclosestDivisors(self, num: int) -> List[int]: ans = [0, int(1e9)] for i inrange(num + 1, num + 3): cur = self.divide(i) ifabs(cur[0] - cur[1]) < abs(ans[0] - ans[1]): ans = cur return ans
[]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { vector<int> ans{}; public: voiddivide(int n){ for (int i = int(sqrt(n)); i != 0; --i) if (n % i == 0) if (abs(n / i - i) < abs(ans[0] - ans[1])) { ans[0] = n / i; ans[1] = i; } } vector<int> closestDivisors(int num){ ans.push_back(0); ans.push_back(1e9); divide(num + 1); divide(num + 2); return ans; } };