Created
April 23, 2015 05:58
-
-
Save otms61/7a1f7d81a90f5267d7cb to your computer and use it in GitHub Desktop.
math utils
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
def gcd(a, b): | |
"""Return greatest common divisor using Euclid's Algorithm.""" | |
while b: | |
a, b = b, a % b | |
return a | |
def lcm(a, b): | |
"""Return lowest common multiple.""" | |
return a * b // gcd(a, b) | |
def egcd(a, b): | |
"""Return x and y such that | |
ax + by = gcd(a, b)""" | |
x, y, u, v = 0, 1, 1, 0 | |
while a != 0: | |
q, r = b // a, b % a | |
m, n = x - u * q, y - v * q | |
b, a, x, y, u, v = a, r, u, v, m, n | |
return b, x, y |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment