Skip to content

Instantly share code, notes, and snippets.

@rileylev
Created July 14, 2021 20:20
Show Gist options
  • Save rileylev/a69f8a9efd78f47ab6decdfb18ea6a18 to your computer and use it in GitHub Desktop.
Save rileylev/a69f8a9efd78f47ab6decdfb18ea6a18 to your computer and use it in GitHub Desktop.
stein's gcd algorithm
#!/usr/bin/env python
def is_even(x):
return x & 1
def gcd(x,y):
factors_of_2 = 0
while true:
if x==0:
return y << factors_of_2
elif y==0:
return x << factors_of_2
elif is_even(x) and is_even(y):
factors_of_2 += 1
x >>= 1
y >>= 1
elif is_even(x):
x >>= 1
elif is_even(y):
y>>=1
else:
mx = max(x,y)
mn = min(x,y)
(x,y) = (mn, mx-mn)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment