Find Greatest Common Divisor of Array

easy array math number theory

Problem

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

Inputnums = [2, 5, 6, 9, 10]
Output2
min = 2, max = 10, gcd(2, 10) = 2.

def find_gcd(nums):
    a, b = min(nums), max(nums)
    while b:
        a, b = b, a % b
    return a
function findGCD(nums) {
  let a = Math.min(...nums), b = Math.max(...nums);
  while (b) {
    [a, b] = [b, a % b];
  }
  return a;
}
class Solution {
    public int findGCD(int[] nums) {
        int a = Integer.MAX_VALUE, b = Integer.MIN_VALUE;
        for (int x : nums) { a = Math.min(a, x); b = Math.max(b, x); }
        while (b != 0) { int t = a % b; a = b; b = t; }
        return a;
    }
}
int findGCD(vector<int>& nums) {
    int a = *min_element(nums.begin(), nums.end());
    int b = *max_element(nums.begin(), nums.end());
    while (b) { int t = a % b; a = b; b = t; }
    return a;
}
Time: O(n + log(max)) Space: O(1)