I don't like the multiple different assignments inside the operator.
They currently all assign to gcd
but you need to study it in detail to work that out.
I would make the assignment explicit and the ternary operator return the correct value.
The other thing with ternary operator is that they are not trivial to read. So use white space to try and make it obvious that it's happening. Also I prefer to explicitly use '{' '}' to make sure that things don't accidentally become associated with the a different statement. I would lay it out like this:
int recursive_euclidean( int num1, int num2 )
{
int gcd;
if( num1 == num2 || num1 < 0 || num2 < 0 )
{
gcd = (num1 == num2)
? num1
: (num1 < 0)
? num2
: num1;
}
else
{
gcd = (num1 > num2)
? recursive_euclidean( num1-num2, num2 )
: recursive_euclidean( num1, num2-num1 );
}
return gcd;
}
Actually reading this again I would refactor more to this:
int recursive_euclidean( int num1, int num2 )
{
int gcd;
if ( num1 == num2)
{ gcd = num1;
}
else if (num1 < 0)
{ gcd = num2;
}
else if (num2 < 0)
{ gcd = num1;
}
else
{
gcd = (num1 > num2)
? recursive_euclidean( num1-num2, num2 )
: recursive_euclidean( num1, num2-num1 );
}
return gcd;
}
Then here, I would not personally not use the ternary operator.
int iterative_euclidean( int num1, int num2 )
{
while( num1 != num2 && num1 > 0 && num2 > 0 )
{
if (num1 > num2 )
{ num1-=num2;}
else{ num2-=num1;}
}
return (num1>0) ? num1 : num2;
}
gcd(2, -2) = 2
is a better choice.gcd(2, -2) = -2
is also correct, as in terms of divisibilityn
and-n
are essentially the same. \$\endgroup\$gcd
computation you need to use the%
operator. \$\endgroup\$