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

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -