Skip to content

1362. Closest Divisors

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
 public:
  vector<int> closestDivisors(int num) {
    for (int root = sqrt(num + 2); root > 0; --root)
      for (int cand : {num + 1, num + 2})
        if (cand % root == 0) return {root, cand / root};

    throw;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
  public int[] closestDivisors(int num) {
    for (int root = (int) Math.sqrt(num + 2); root > 0; --root)
      for (int cand : new int[] {num + 1, num + 2})
        if (cand % root == 0)
          return new int[] {root, cand / root};

    throw new IllegalArgumentException();
  }
}
1
2
3
4
5
6
class Solution:
  def closestDivisors(self, num: int) -> List[int]:
    for root in reversed(range(int(sqrt(num + 2)) + 1)):
      for cand in [num + 1, num + 2]:
        if cand % root == 0:
          return [root, cand // root]