返回介绍

solution / 1300-1399 / 1362.Closest Divisors / README_EN

发布于 2024-06-17 01:03:20 字数 3617 浏览 0 评论 0 收藏 0

1362. Closest Divisors

中文文档

Description

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 1:

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.

Example 2:

Input: num = 123
Output: [5,25]

Example 3:

Input: num = 999
Output: [40,25]

 

Constraints:

  • 1 <= num <= 10^9

Solutions

Solution 1: Enumeration

We design a function $f(x)$ that returns two numbers whose product equals $x$ and the absolute difference between these two numbers is the smallest. We can start enumerating $i$ from $\sqrt{x}$. If $x$ can be divided by $i$, then $\frac{x}{i}$ is another factor. At this point, we have found two factors whose product equals $x$. We can return them directly. Otherwise, we decrease the value of $i$ and continue to enumerate.

Next, we only need to calculate $f(num + 1)$ and $f(num + 2)$ respectively, and then compare the return values of the two functions. We return the one with the smaller absolute difference.

The time complexity is $O(\sqrt{num})$, and the space complexity is $O(1)$. Where $num$ is the given integer.

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
class Solution {
  public int[] closestDivisors(int num) {
    int[] a = f(num + 1);
    int[] b = f(num + 2);
    return Math.abs(a[0] - a[1]) < Math.abs(b[0] - b[1]) ? a : b;
  }

  private int[] f(int x) {
    for (int i = (int) Math.sqrt(x);; --i) {
      if (x % i == 0) {
        return new int[] {i, x / i};
      }
    }
  }
}
class Solution {
public:
  vector<int> closestDivisors(int num) {
    auto f = [](int x) {
      for (int i = sqrt(x);; --i) {
        if (x % i == 0) {
          return vector<int>{i, x / i};
        }
      }
    };
    vector<int> a = f(num + 1);
    vector<int> b = f(num + 2);
    return abs(a[0] - a[1]) < abs(b[0] - b[1]) ? a : b;
  }
};
func closestDivisors(num int) []int {
  f := func(x int) []int {
    for i := int(math.Sqrt(float64(x))); ; i-- {
      if x%i == 0 {
        return []int{i, x / i}
      }
    }
  }
  a, b := f(num+1), f(num+2)
  if abs(a[0]-a[1]) < abs(b[0]-b[1]) {
    return a
  }
  return b
}

func abs(x int) int {
  if x < 0 {
    return -x
  }
  return x
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文