Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ Greatest Common Divisor

I am very new to C++ and am attempting create a function to implement the Euclidean algorithm that returns the greatest common divisor for two integer inputs.

The current approach I am taking keeps crashing - can you help me understand why?

int main() {    
    int a = 0;
    int b = 0;

    cin >>  a;
    cin >> b;

    do {
        if ( a > b ) a = a % b;
        else if ( a < b ) b = b % a;
        else if ( a == b ) break;
    } while ( ( a || b ) != 0 ); 

    return 0;
}

Thanks,

David

like image 305
David Loughnane Avatar asked Dec 05 '22 22:12

David Loughnane


1 Answers

while ( ( a || b ) != 0 ); 

this is wrong. It should be

while ( a != 0 && b != 0 ); 

On a side note, the Euclid's algorithm can be concisely implemented recursively:

int gcd(int a, int b)
{
   return b == 0 ? a : gcd(b, a%b);
}
like image 191
Armen Tsirunyan Avatar answered Dec 21 '22 17:12

Armen Tsirunyan