Closest Divisors
To find the closest divisors of num + 1
or num + 2
, you can use the following algorithm:
Calculate Targets: The two target numbers for which you need to find divisors are
num + 1
andnum + 2
.Find Divisors: For each target number, find its divisors. Start from the square root of the target number and iterate downwards. If a number
i
divides the target number, then the divisors arei
andtarget // i
.Compare Differences: Compare the absolute differences between the divisors for both target numbers and choose the pair with the smaller absolute difference.
Return Result: Return the divisors for the target number with the smaller absolute difference.
Here’s the code:


The above code calculates the divisors by starting from the square root and iterating downwards, ensuring an efficient calculation. The time complexity is O(sqrt(n)) for finding the divisors of each target, leading to an overall time complexity of O(sqrt(n)). The space complexity is O(1).