/* ***** BEGIN LICENSE BLOCK ***** * Version: GPL 2.0 * * gcd.c : an implementation of the Euclidean Algorithm * Copyright (C) 2007 Adam Dane * * First Edit: 2007.10.11 * Last Edit: 2007.10.12 * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * ***** END LICENSE BLOCK ***** */ #include #include #include #include int main(int argc, char **argv) { int a,b,r; //declare variables if (argc < 3) { printf("usage: gcd where neither == 0\n"); exit(-1); } b = strtol(argv[1], NULL, 10); // get values from command line if (errno != 0 && (b == LONG_MIN || b == LONG_MAX)) // ensure valid input { perror("Bad argument"); exit(-1); } r = strtol(argv[2], NULL, 10); if (errno != 0 && (r == LONG_MIN || r == LONG_MAX)) { perror("Bad argument"); exit(-1); } if (b < r) // order them properly { a = r; r = b; b = a; } while (r != 0) // keep going until GCD found (worst case it's 1) { a = b; // shuffle values to correct spots b = r; if ((r = a % b) == 0) // compute the remainder, if it's 0 then GCD found { printf("The GCD is: %d\n", b); exit(0); } } printf("usage: gcd where neither == 0\n"); exit(-1); }