1979. Find Greatest Common Divisor of Array (Leetcode Easy)

preview_player
Показать описание
Larry solves and analyzes this Leetcode problem as both an interviewer and an interviewee. This is a live recording of a real engineer solving a problem live - no cuts or edits!

#leetcode #coding #programming
Рекомендации по теме
Комментарии
Автор

def findGCD(nums):
# This line finds the smallest (min(nums)) and largest (max(nums)) numbers in the list nums
# and assigns them to a and b, respectively.
a, b = min(nums), max(nums)
# This inner function gcd(a, b) calculates the GCD of two numbers
# a and b using the Euclidean algorithm.
# Euclidean Algorithm:
# While both a and b are greater than 0, it repeatedly reduces the larger number by setting
# it to its remainder when divided by the smaller number.
# This continues until one of the numbers becomes 0.
# The GCD is the non-zero number remaining when the other becomes 0.
def gcd(a, b):
# while a > 0 and b > 0: This loop runs as long as both a and b are positive.
# Inside the loop, it uses the modulus operation to reduce the larger number:
# The loop iteratively reduces the values until one becomes 0.
while a > 0 and b > 0:
# if a > b: a = a % b: If a is greater, it is reduced by b.
if a > b:
a = a % b
# else: b = b % a: Otherwise, b is reduced by a.
else:
b = b % a
# If a becomes 0, the function returns b, which is the GCD.
if a == 0:
return b
# If b becomes 0, the function returns a, which is the GCD.
else:
return a
# This line calls the gcd function with the previously determined smallest and largest values
# from the list and returns the GCD.
return gcd(a, b)
Thank me later larry

maharshibiswas