Introduction

Topics

GCD

Implementation

For two numbers:

"""
@complexity:
Time:  O(min(a,b))
Space: O(1)
"""
#iteratively 
def gcd(a, b):
    result = min(a, b)
 
    while result:
        if a % result == 0 and b % result == 0:
            break
        result -= 1
 
    return result

# recursively
def gcd(a,b):
    if a == 0:
        return b
    return gcd(b % a, a)
"""
@complexity:
Time:  O(min(a,b))
Space: O(1)
"""
# recursively
def gcd(a, b):
    if (a == 0):
        return b
    if (b == 0):
        return a

    if (a == b):
        return a
 
    if (a > b):
        return gcd(a-b, b)
    return gcd(a, b-a)
"""
@complexity:
Time:  O(log(min(a,b)))
Space: O(log(min(a,b)))
"""
# recursively
def gcd(a,b):
    
    if (b == 0):
         return a
    return gcd(b, a%b)

For more numbers:


Prime Factorization and Divisors

LCM (Least Common Multiple)