data-structures · intermediate · ~15 min
Compute a GCD with the Euclidean recurrence.
Implement:
int gcd(int a, int b);
Return the greatest common divisor of a and b (both >= 0) using the recursive Euclidean algorithm.
a, b >= 0.
gcd(a,b).
gcd(x,0)=x.
#include <stddef.h>
/* Greatest common divisor of a and b (a,b >= 0), via the recursive Euclidean algorithm. */
int gcd(int a,int b){ (void)a;(void)b; return 1; }
Wrong base case; recursing with the wrong pair.
gcd(0,0)=0; order of arguments doesn't matter.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.