Since GCD is associative, GCD(a,b,c,d)
is the same as GCD(GCD(GCD(a,b),c),d)
. In this case, Python's reduce
function would be a good candidate for reducing the cases for which len(numbers) > 2
to a simple 2-number comparison. The code would look something like this:
if len(numbers) > 2:
return reduce(lambda x,y: GCD([x,y]), numbers)
Reduce applies the given function to each element in the list, so that something like
gcd = reduce(lambda x,y:GCD([x,y]),[a,b,c,d])
is the same as doing
gcd = GCD(a,b)
gcd = GCD(gcd,c)
gcd = GCD(gcd,d)
Now the only thing left is to code for when len(numbers) <= 2
. Passing only two arguments to GCD
in reduce
ensures that your function recurses at most once (since len(numbers) > 2
only in the original call), which has the additional benefit of never overflowing the stack.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…