Magicsheet logo

Closest Divisors

Medium
25%
Updated 8/1/2025

Asked by 1 Company

Topics

Closest Divisors

What is this problem about?

The Closest Divisors interview question asks you to find two integers whose product is either num + 1 or num + 2, such that the absolute difference between these two integers is as small as possible. You are given a single integer num as input. The goal is to return the pair of divisors that are "closest" to each other, effectively finding the two factors that are nearest to the square root of the target number.

Why is this asked in interviews?

Amazon and other companies use the Closest Divisors coding problem to test a candidate's proficiency with mathematical logic and basic number theory. It’s a great problem to see if a candidate can optimize a search. A naive approach might check all numbers from 1 to num, but an efficient solution leverages the property that divisors come in pairs and the closest pair will be found near the square root.

Algorithmic pattern used

The primary Math interview pattern used here is Square Root Optimization. To find the closest divisors of a number X, you should start checking from floor(sqrt(X)) and move downwards towards 1. The first factor you find will automatically be part of the "closest" pair because you are starting from the point where the two factors would be most equal (i.e., the square root).

Example explanation

Suppose num = 8. We need to check divisors for num + 1 = 9 and num + 2 = 10.

  1. For 9: sqrt(9) = 3. 3 * 3 = 9. Difference is 3 - 3 = 0.
  2. For 10: sqrt(10) \approx 3.16.
    • Start at 3: 10 % 3 != 0.
    • Try 2: 10 % 2 == 0. Pair is [2, 5]. Difference is 5 - 2 = 3. Comparing the two, [3, 3] has a smaller difference than [2, 5]. The result is [3, 3].

Common mistakes candidates make

  • Checking both numbers separately: Not realizing that you can just find the best pair for num+1 and num+2 and then compare them.
  • Linear Search: Starting from 1 and going up to num, which is O(N) instead of O(sqrt(N)).
  • Integer Overflow: Although less common here, always be mindful of product calculations in languages with fixed integer sizes.

Interview preparation tip

Whenever a problem involves finding pairs of factors or divisors, always think about the square root as the turning point. It's the most common optimization for number theory problems.

Similar Questions