hey guys, i've been having problems with a exercise in my homework, its a greatest common divisor method that is recursive, but the instructor said to use the binary way, i think its called like that , where if
-A is even and B is even then GCD(A/2,B/2)
-A is odd and B is even then GCD(A,B/2)
-A is even and B is odd then GCD(A/2,B)
and here is my code :
what do you guys think is the problem.
-A is even and B is even then GCD(A/2,B/2)
-A is odd and B is even then GCD(A,B/2)
-A is even and B is odd then GCD(A/2,B)
and here is my code :
public static long gcd( long a , long b ) {
//assert ( a % 2 == 0 || b % 2 == 0 );
if ( a == b ) {
return a;
}
else if ( a % 2 == 0 && b % 2 == 0 ) return 2 * gcd( a / 2 , b / 2 );
else if ( a % 2 == 0 && b % 2 == 1 ) return gcd( a / 2 , b );
else if ( a % 2 == 1 && b % 2 == 0 ) return gcd( a / 2 , b );
//assert ( a % 2 == 1 && b % 2 == 1 );
else {
if ( a == 0 ) return b;
if ( b == 0 ) return a;
if ( a > b ) return gcd( b , a % b );
return gcd( a , b % a );
}
}
my problem is that its giving StackOverFlowException at the third else if. what do you guys think is the problem.