/* gcd.c - simple example of calculating GCD (greatest common divisor * Jon Mayo - PUBLIC DOMAIN - July 24, 2007 */ #include #include int main(int argc, char **argv) { long a, b; if(argc!=3) { fprintf(stderr, "Usage: %s \n", argv[0]); return EXIT_FAILURE; } a=strtol(argv[1], 0, 0); b=strtol(argv[2], 0, 0); if(a==0 && b==0) { printf("gdc=N/A\n"); return EXIT_FAILURE; } /* subtract smallest from largest in a loop. swap to keep b the smallest. * result of GDC will be in a (the largest) */ while(b!=0) { /* printf("a=%ld\n", a); */ if(a>=b) { a-=b; } else { /* swap(a,b) */ a^=b; b^=a; a^=b; } } printf("gdc=%ld\n", a); return 0; }