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
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With