题目链接
提供一个数num,要求从num+1和num+2中找到两个数a和b,且满足下面条件
- a * b = num + 1 or num + 2
- abs(a - b)最小
针对num+1和num+2分别处理,设它俩为target
从[sqrt(target), 1]区间内,找到a使得target mod a == 0
b = target / a
时间复杂度
O(num)
Runtime: 20 ms (beats 79.27%)
Memory Usage: 1.9 MB
func closestDivisors(num int) []int {
ans := []int{0, math.MaxInt32}
process := func(num int) {
sqrt := int(math.Sqrt(float64(num))) + 1
for i := sqrt; i >= 1; i-- {
if num % i == 0 {
if math.Abs(float64(ans[0] - ans[1])) > math.Abs(float64(num / i - i)) {
ans[0] = i
ans[1] = num / i
}
break
}
}
}
process(num + 1)
process(num + 2)
return ans
}