Closest Divisors Problem
Description
LeetCode Problem 1362.
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
Solution
Approach: Search Down from the Square Root
Handle num + 1 and num + 2 separately: for each, find its factor pair (a, b) with a * b = x and the smallest difference, then return the pair with the smaller difference of the two.
For a fixed x, write the pair as a <= b. Then a <= sqrt(x), and as a grows toward sqrt(x), b = x / a shrinks toward it, so the difference b - a gets smaller. So the best pair is the one with the largest divisor a not exceeding sqrt(x). Start at a = floor(sqrt(x)) and count down until a divides x. This always stops, at a = 1 at the latest.
In Example 1, 9 = 3 * 3 (difference 0) beats 10 = 2 * 5 (difference 3), so the answer is [3, 3].
The worst case is when both numbers have no divisor near their square root (for example, num + 2 is prime): the loop then runs about sqrt(num), around 31623 times, which is still fast.
num + 2 is at most 109 + 2, which still fits in a 32-bit int, so no overflow handling is needed.
Complexity: O(sqrt(num)) time and O(1) space.
import math
class Solution:
def closestDivisors(self, num: int) -> List[int]:
def closest_pair(x: int) -> List[int]:
# The closest factor pair has its smaller factor as near to sqrt(x) as possible.
for i in range(math.isqrt(x), 0, -1):
if x % i == 0:
return [i, x // i]
a = closest_pair(num + 1)
b = closest_pair(num + 2)
return a if a[1] - a[0] < b[1] - b[0] else b