Created
July 24, 2017 22:39
-
-
Save kanglicheng/f196d251ad68e51253c1afdc20648a49 to your computer and use it in GitHub Desktop.
calculating gcd and lcm of two numbers, using reduce for multiple numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#using python 3.5 | |
import functools | |
# standard euclidean algorithm | |
def gcd(a, b): | |
while b: | |
a, b = b, a%b | |
return a | |
# with explicit recursion | |
def gcd_multiple(a, b): | |
if b==0: | |
return a | |
else: | |
return gcd_multiple(b, a%b) | |
# calculating the gcd of more than two numbers | |
def gcd_multiple(*args): | |
return functools.reduce(lambda x, y:gcd(x, y), args) | |
#modify to accomodate numbers in a list (array) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment