GCD

Feb 9, 2015 at 3:01am
What is wrong with this GCD program?
1
2
3
4
int gcd(int a, int b){
    if(b==0) return a;
    return gcd(b,b%a);
}


If I change return gcd(b,b%a) to return gcd(b,a%b) it works. In the examples I am trying both the algorithms work, but when I use this gcd method on online coding problem, return gcd(b,a%b) works but not the other. Can someone throw some light and provide an example where return gcd(b,b%a) fails?

Feb 9, 2015 at 4:57am
Possibly if a is 0, b%a would fail. Whereas in a%b, b cannot be 0 because of the return statement in if(b==0).
Last edited on Feb 9, 2015 at 4:59am
Feb 9, 2015 at 5:06am
Wow, good point @kevinkjt2000. That explains thanks :)
Feb 9, 2015 at 6:31am
1
2
3
4
5
6
7
8
9
int gcd(int a, int b){
	int GCD;
	for(int i=1; i<=a && i<=b; i++){
		if(a%i==0 && b%i==0){
			GCD=i;
		}
	}
return GCD;	
}
Feb 9, 2015 at 6:35pm
@anup30: your example will return undefined values when either a or b is less than or equal to 0
Last edited on Feb 10, 2015 at 6:13pm
Feb 10, 2015 at 8:58am
gcd(0,a) = a (wikipedia)
1
2
3
4
5
6
7
8
9
10
11
int gcd(int a, int b){
	if(a==0) return b;
	if(b==0) return a;
	int GCD;
	for(int i=1; i<=a && i<=b; i++){
		if(a%i==0 && b%i==0){
			GCD=i;
		}
	}
return GCD;	
}
Topic archived. No new replies allowed.