Created
October 22, 2011 02:31
-
-
Save davorb/1305468 to your computer and use it in GitHub Desktop.
This file contains 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_recursive(u, v) | |
return u|v if u==0 or v==0 | |
if u.even? | |
if v.even? | |
return gcd(u>>1, v>>1)<<1 | |
else | |
return gcd(u>>1, v) if v.odd? | |
end | |
elsif u.odd? and v.even? | |
return gcd(u, v>>1) | |
else | |
if u < v | |
u, v = v, u | |
end | |
return gcd((u-v)>>1, v) | |
end | |
end | |
def gcd(u, v) | |
return u|v if u==0 or v==0 | |
shift=0 | |
while ((u|v)&1)==0 do | |
u=u >> 1; | |
v=v >> 1; | |
shift += 1 | |
end | |
while ((u&1) == 0) do | |
u=u >> 1 | |
end | |
begin | |
while ((v & 1) == 0) do | |
v=v >> 1 | |
end | |
if u < v | |
v -= u | |
else | |
diff = u - v | |
u = v | |
v = diff | |
end | |
end while v != 0 | |
u<<shift | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment