c++ - binary gcd algorithm - not working -
i read binary gcd algorithm , tried implement .it worked. code
int gcd2(int a, int b) { int sh; if (a == 0) return b; if (b == 0) return a; (sh = 0; !((a | b) & 1); sh++) { >>= 1; b >>= 1; } while (!(a & 1)) { >>= 1; } while(b) { while (!(b & 1)) { b >>= 1; } if (a > b) { int t = a; = b; b = t; } b = b - a; } return << sh; }
but doesn't work if replace last if with
if (b > a) { int t = a; = b; b = t; } b = -b;
i thought both should work since doing same.but doesn't work. can explain please?
thanks in advance!
it not same: if choose second way, there chance stays bigger b. never svap variables, , b less after b=a-b, if b positive
i think using
a=a-b
instead of
b=a-b
could it
Comments
Post a Comment