Given an array of positive integers nums, return the greatest common divisor (GCD) of all the elements in the array.
The GCD of a set of integers is the largest positive integer that divides each of the integers without leaving a remainder.
Function Signature
def find_gcd(nums: list[int]) -> int:
Rules
-
When
nums
has a single element, the answer is that element.
Constraints
-
1 <= len(nums) <= 10^4
-
1 <= nums[i] <= 10^9
Examples
Input: nums = [12, 18, 24]
Output: 6
gcd(12, 18) = 6, then gcd(6, 24) = 6. In prime factors, 12 = 2^2 · 3, 18 = 2 · 3^2 and 24 = 2^3 · 3, and the shared part is 2 · 3 = 6.
Input: nums = [7, 14, 21, 28]
Output: 7
All numbers are multiples of 7, so the GCD is 7. It cannot be larger, because the GCD never exceeds the smallest element.
Input: nums = [6, 9, 18]
Output: 3
gcd(6, 9) = 3, and 3 divides 18. The smallest and largest values alone (6 and 18) have GCD 6, but 6 does not divide 9, so every element has to be included.