Closest Divisors - Problem
Finding the Perfect Factor Pair
Given an integer
Goal: Return the two integers whose product equals either
Example: For
•
•
The answer is
Given an integer
num, you need to find two divisors that are as close to each other as possible. However, there's a twist! You can choose to find divisors for either num + 1 or num + 2 - whichever gives you the closest pair.Goal: Return the two integers whose product equals either
num + 1 or num + 2 and have the smallest absolute difference between them.Example: For
num = 8, you can choose between:•
9 = 1 × 9 (difference: 8) or 9 = 3 × 3 (difference: 0)•
10 = 1 × 10 (difference: 9) or 10 = 2 × 5 (difference: 3)The answer is
[3, 3] since they have the smallest difference of 0. Input & Output
example_1.py — Basic Case
$
Input:
num = 8
›
Output:
[3, 3]
💡 Note:
For num=8, we check num+1=9 and num+2=10. For 9: divisors are (1,9) with diff=8, (3,3) with diff=0. For 10: divisors are (1,10) with diff=9, (2,5) with diff=3. The smallest difference is 0 from [3,3].
example_2.py — Another Case
$
Input:
num = 123
›
Output:
[5, 25]
💡 Note:
For num=123, we check 124 and 125. For 124: closest divisors near √124≈11.1 are found by checking down from 11. For 125: 125=5×25, and √125≈11.2, so checking from 11 down we find 5×25 with difference |5-25|=20. After comparing both, [5,25] gives the minimum difference.
example_3.py — Edge Case
$
Input:
num = 999
›
Output:
[25, 40]
💡 Note:
For num=999, we check 1000 and 1001. 1000=25×40 (diff=15), while 1001=7×143 (diff=136). The optimal pair is [25,40] with difference 15.
Visualization
Tap to expand
Understanding the Visualization
1
Two Sheets Available
You have sheets of size num+1 and num+2 square units
2
Find Square Root
Calculate √(sheet_size) to find the ideal square dimensions
3
Search Downward
Starting from √n, find the first valid divisor going down
4
Compare Results
Pick the rectangle closest to square from both sheets
Key Takeaway
🎯 Key Insight: The closest divisors are always found near the square root! This transforms an O(n) brute force into an elegant O(√n) solution.
Time & Space Complexity
Time Complexity
O(√n)
We only check divisors from sqrt(n) down to 1, and stop at the first match
✓ Linear Growth
Space Complexity
O(1)
Only using a few variables to store results
✓ Linear Space
Constraints
- 1 ≤ num ≤ 109
- Output format: Return any valid pair as [a, b] where a×b = num+1 or num+2
- The returned pair should have the minimum absolute difference |a-b|
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code