I read the binary gcd algorithm and tried to implement it .It worked. This is my code
int gcd2(int a, int b) {
int sh;
if (a == 0)
return b;
if (b == 0)
return a;
for (sh = 0; !((a | b) & 1); sh++) {
a >>= 1;
b >>= 1;
}
while (!(a & 1)) {
a >>= 1;
}
while(b) {
while (!(b & 1)) {
b >>= 1;
}
if (a > b) {
int t = a;
a = b;
b = t;
}
b = b - a;
}
return a << sh;
}
But doesn't work if I replace the last if with
if (b > a)
{
int t = a;
a = b;
b = t;
}
b = a -b;
I just thought that both should work since they are doing the same.But it doesn't work. Can anyone explain it please?
Thanks in advance!
it is not the same: if you choose your second way, there is the chance that a always stays bigger then b. then you never get to svap variables, and b is always less then a after b=a-b, if b is positive
i think using
a=a-b
instead of
b=a-b
could do it