返回介绍

solution / 1900-1999 / 1979.Find Greatest Common Divisor of Array / README_EN

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

1979. Find Greatest Common Divisor of Array

中文文档

Description

Given an integer array nums, return _the greatest common divisor of the smallest number and largest number in _nums.

The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.

 

Example 1:

Input: nums = [2,5,6,9,10]
Output: 2
Explanation:
The smallest number in nums is 2.
The largest number in nums is 10.
The greatest common divisor of 2 and 10 is 2.

Example 2:

Input: nums = [7,5,6,8,3]
Output: 1
Explanation:
The smallest number in nums is 3.
The largest number in nums is 8.
The greatest common divisor of 3 and 8 is 1.

Example 3:

Input: nums = [3,3]
Output: 3
Explanation:
The smallest number in nums is 3.
The largest number in nums is 3.
The greatest common divisor of 3 and 3 is 3.

 

Constraints:

  • 2 <= nums.length <= 1000
  • 1 <= nums[i] <= 1000

Solutions

Solution 1

class Solution:
  def findGCD(self, nums: List[int]) -> int:
    return gcd(max(nums), min(nums))
class Solution {
  public int findGCD(int[] nums) {
    int a = 1, b = 1000;
    for (int x : nums) {
      a = Math.max(a, x);
      b = Math.min(b, x);
    }
    return gcd(a, b);
  }

  private int gcd(int a, int b) {
    return b == 0 ? a : gcd(b, a % b);
  }
}
class Solution {
public:
  int findGCD(vector<int>& nums) {
    int a = *max_element(nums.begin(), nums.end());
    int b = *min_element(nums.begin(), nums.end());
    return gcd(a, b);
  }
};
func findGCD(nums []int) int {
  a, b := slices.Max(nums), slices.Min(nums)
  return gcd(a, b)
}

func gcd(a, b int) int {
  if b == 0 {
    return a
  }
  return gcd(b, a%b)
}
function findGCD(nums: number[]): number {
  let a = 1;
  let b = 1000;
  for (const x of nums) {
    a = Math.max(a, x);
    b = Math.min(b, x);
  }
  return gcd(a, b);
}

function gcd(a: number, b: number): number {
  if (b == 0) {
    return a;
  }
  return gcd(b, a % b);
}

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

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

发布评论

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