
Python GCD - How to get GCD of 2 integers or a list
The simplest way to get GCD of 2 integers is importing math
module and using gcd
function.
import math
g = math.gcd(6, 8)
print(g) # 2
But gcd
can't calculate GCD of more than 3 integers.
import math
g = math.gcd(6, 8, 10)
# TypeError: gcd expected 2 arguments, got 3
How to get GCD of more than 3 integers
You can calculate GCD of a list with reduce in functools
module.
import math
from functools import reduce
a = [24, 16, 40]
g = reduce(math.gcd, a)
print(g) # 8
reduce
repeats the process of
- applying
math.gcd
to the first 2 items ofa
and getting the value (8
) - removing these items from
a
- putting
8
to the beginnging ofa
To put it simply:
- math.gcd(24, 16) -> 8
- math.gcd(8, 40) -> 8
Comments
Powered by Markdown