/* * gcd -- compute the GCD of pairs of integers * * History * 1.0 Matt Bishop; original program * 1.1 Matt Bishop; made it recursive */ #include /* * macros */ #define BAD_GCD -1 /* error in arguments -- */ /* MUST be non-positive */ /* * recursive GCD */ int gcdr(int m, int n) { /* base case(s) */ if (m == 0) return(n); if (n == 0) return(m); /* now recurse */ return(gcdr(n, m % n)); } /* * This function returns the greatest common divisor of its arguments * Notes: (1) if m = n = 0, the GCD is undefined -- so we return BAD_GCD * (2) if m < 0 or n < 0, then gcd(m,n) > 0; so we can just make * m and n both positive * (3) if m = 0 and n != 0, gcd(m,n) = n (and vice versa) */ int gcd(int m, int n) { /* * special cases */ /* error check -- if both 0, undefined */ if (m == 0 && n == 0) return(BAD_GCD); /* make all negatives positive */ if (m < 0) m = -m; if (n < 0) n = -n; /* * now apply the recursive algorithm */ return(gcdr(m, n)); } /* * the main routine */ void main(void) { int m, n; /* numbers to take the GCD of */ int g; /* the GCD of m and n */ int c; /* used to gobble up rest of line */ /* * loop, asking for numbers and printing the GCD */ while(printf("Enter two numbers: "), scanf("%d %d", &m, &n) != EOF){ while((c = getchar()) != EOF && c != '\n') ; /* print the result -- note that if the input */ /* is invalid, gcd() simply returns BAD_GCD */ printf("The GCD of %d and %d is ", m, n); if ((g = gcd(m, n)) == BAD_GCD) printf("undefined.\n"); else printf("%d.\n", g); } /* * clean up output and exit */ putchar('\n'); exit(0); }