Skip to content

Commit

Permalink
Binary GCD
Browse files Browse the repository at this point in the history
  • Loading branch information
detel committed Jul 15, 2015
1 parent 1eec6b6 commit a5583a7
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions Binary GCD.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
def gcd_bin(u, v):
u, v = abs(u), abs(v)
if u < v:
u, v = v, u
if v == 0:
return u

k = 1
while u & 1 == 0 and v & 1 == 0:
u >>= 1
v >>= 1
k <<= 1

t = -v if u & 1 else u
while t:
while t & 1 == 0:
t >>= 1
if t > 0:
u = t
else:
v = -t
t = u - v
return u*k

print gcd_bin(2334680,789785665)

0 comments on commit a5583a7

Please sign in to comment.