MediumNo. 1362

Closest Divisors — LeetCode 1362 Python Solution

Topics
Math
Reading time
2 min

The 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

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.

Python solution

PythonSolution
class Solution:
    def closestDivisors(self, num: int) -> List[int]:
        def f(x):
            for i in range(int(sqrt(x)), 0, -1):
                if x % i == 0:
                    return [i, x // i]

        a = f(num + 1)
        b = f(num + 2)
        return a if abs(a[0] - a[1]) < abs(b[0] - b[1]) else b

Complexity

Time
O(√num)
Space · auxiliary
O(1)

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 1362. Closest Divisors is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
1360Number of Days Between Two DatesEasy
0002Add Two NumbersMedium
0007Reverse IntegerMedium
0009Palindrome NumberEasy
0043Multiply StringsMedium
0048Rotate ImageMedium

Frequently asked questions

How hard is LeetCode 1362. Closest Divisors?

LeetCode 1362. Closest Divisors is rated Medium on LeetCode.

What is the time complexity of LeetCode 1362. Closest Divisors?

The Python solution on this page runs in O(√num).

What is the space complexity of LeetCode 1362. Closest Divisors?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 1362. Closest Divisors cover?

LeetCode 1362. Closest Divisors is tagged Math on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.