You need to find the Greatest Common Divisor (GCD) of an array of numbers. The GCD of an array is the largest positive integer that divides each of the integers in the array without leaving a remainder.
Input: nums = [2,5,6,9,10]
Output: 1
Input: nums = [7,5,6,8,3]
Output: 1
Input: nums = [3,3]
Output: 3
math
Library: Python’s math
library contains a convenient gcd
function.import math
from functools import reduce
def findGCD(nums):
return reduce(math.gcd, nums)
# Example usage:
nums1 = [2, 5, 6, 9, 10]
print(findGCD(nums1)) # Output: 1
nums2 = [7, 5, 6, 8, 3]
print(findGCD(nums2)) # Output: 1
nums3 = [3, 3]
print(findGCD(nums3)) # Output: 3
n
is the length of the array. The GCD operation for two numbers a
and b
takes O(log(min(a, b))), and we are doing this n-1
times.This ensures the solution is efficient and meets the problem’s constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?