For those who don't know, GCD(u,v) is the greatest common denominator between u and v. That is, the largest number that goes into both of them.
A good application is simplifying fractions. Suppose we have a fraction a/b that is not simplified. Then we could easily simplify by calculating c = GCD(a,b), and then setting x = a/c and y = b/c, which gives us the fraction x/y, which is indeed equal to (albeit simpler than) a/b.
Anyway, onto the code.
Code: Select all
'binary GCD function
function gcd(u as uinteger, v as uinteger) as uinteger
dim as uinteger sft=0, tmp=0
if (u*v = 0) then return 0
while (((u or v) and 1) = 0)
sft += 1
u shr= 1
v shr= 1
wend
while ((u and 1) = 0)
u shr= 1
wend
do
while ((v and 1) = 0)
v shr= 1
wend
if (u < v) then
v -= u
else
tmp = u - v
u = v
v = tmp
end if
v shr= 1
loop while (v <> 0)
return (u shl sft)
end function