C ++ The biggest common divisor

I am very new to C ++ and trying to create a function to implement the Euclidean algorithm that returns the largest common factor for two integer inputs.

The current approach that I take continues to fail - 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;
}

Thank,

David

+4
source share
4 answers
while ( ( a || b ) != 0 ); 

it is not right. It should be

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

On the other hand, the Euclidean algorithm can be briefly implemented recursively:

int gcd(int a, int b)
{
   return b == 0 ? a : gcd(b, a%b);
}
+9
source

Your term ( a || b ) != 0will not be resolved as you expect.
What you want to do is (a != 0) && (b != 0)
Or just as it Cheers and hth. - Alfoffers a && b.

+3
source

. .

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

.

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

, . -

int main() {

int a, b, r;

cin >> a;
cin >> b;

while ( b != 0) {
    r = a % b;
    a = b;
    b = r;
}

cout << "The GCD is " << a << endl;

}

, . libstd++. Libstd++

+1

, , , while ( ( a || b ) != 0 )?

( a || b ) != 0. C/++ , () , :

bool r1 = a || b;  // intermediate result
bool r2 = r1 != 0;
while(r2);

:

  • a || b true, a, b .
  • r1
    • true 1
    • false 0
  • r1 != 0 (true false)
  • while , .
+1
source

All Articles