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
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); }
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.
( a || b ) != 0
(a != 0) && (b != 0)
Cheers and hth. - Alf
a && b
. .
.
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++
, , , while ( ( a || b ) != 0 )?
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
1
false
0
r1 != 0
while