Closest Divisors - Problem

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: If num = 8, we need to find two integers whose product is either 9 or 10. For 9: divisors are [1,9] and [3,3]. For 10: divisors are [1,10], [2,5]. The closest pair is [3,3] with difference 0.

Input & Output

Example 1 — Perfect Square Case
$ Input: num = 8
Output: [3,3]
💡 Note: For num+1=9: divisors are [1,9] and [3,3]. For num+2=10: divisors are [1,10], [2,5]. The closest pair is [3,3] with difference 0.
Example 2 — Small Number
$ Input: num = 2
Output: [2,2]
💡 Note: For num+1=3: divisors are [1,3]. For num+2=4: divisors are [1,4], [2,2]. The closest pair is [2,2] with difference 0.
Example 3 — Prime Result
$ Input: num = 10
Output: [3,4]
💡 Note: For num+1=11: divisors are [1,11] (11 is prime). For num+2=12: divisors include [3,4]. The closest pair is [3,4] with difference 1.

Constraints

  • 1 ≤ num ≤ 109

Visualization

Tap to expand
Closest Divisors Square Root Optimization Approach INPUT num = 8 Given Integer Target Products: num + 1 = 9 num + 2 = 10 GOAL: Find two integers a, b where a*b = 9 or 10, minimize |a-b| 1 <= num <= 10^9 ALGORITHM STEPS 1 Start from sqrt(num+2) i = floor(sqrt(10)) = 3 2 Check divisibility If (num+1)%i==0 or (num+2)%i==0 3 Decrement i Loop: i-- until divisor found 4 Return closest pair Return [i, product/i] Iteration Check (i=3): 9 % 3 = 0 OK! Divisors: 3 and 9/3 = 3 Difference: |3-3| = 0 BEST! FINAL RESULT Closest Divisors Found: 3 x 3 3 x 3 = 9 9 = num + 1 = 8 + 1 Absolute Difference: |3 - 3| = 0 (Minimum!) Output: [3, 3] Key Insight: Starting from sqrt(num+2) and decrementing ensures we find the closest pair first. Factors closest to the square root have the smallest difference. Time complexity: O(sqrt(n)) For perfect squares like 9, the divisors are equal (3,3), giving difference = 0. TutorialsPoint - Closest Divisors | Square Root Optimization
Asked in
Facebook 25 Amazon 20
32.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen