Find the Greatest Common Divisor of All Elements in an Array

Quick Overview

Return the greatest common divisor of every element in an array of up to ten thousand positive integers. It tests whether you can extend the two-number Euclidean algorithm to a whole array, justify why the approach is correct, and handle cases where checking only some of the elements gives the wrong result.

Find the Greatest Common Divisor of All Elements in an Array

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

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 ```python 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 ```text 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. ```text 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. ```text 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.

Overview: Return the greatest common divisor of every element in an array of up to ten thousand positive integers. It tests whether you can extend the two-number Euclidean algorithm to a whole array, justify why the approach is correct, and handle cases where checking only some of the elements gives the wrong result.

Nov 25, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

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.