/********************************************************************** * Compute the GCD of two integers in base 10 given on the command line. * * Usage: * gcd_euclidean * * You may compile the source using GCC 4.x as follows: * gcc -std=c99 -pedantic -Wall -Wextra gcd_euclidean.c -o gcd_euclidean **********************************************************************/ #include #include #include #include #define NUM_ARGS_NEEDED 3 /********************************************************************** * Get the GCD of two numbers using the Euclidean Algorithm. * * Parameters: * num1 -- the first number * num2 -- the second number * * Returns: * The GCD of the two numbers, or 0 on error. **********************************************************************/ long long get_gcd_euclidean(long long num1, long long num2) { // Temporary variable for swapping the numbers if we need to long long temp; // The remainder of the two numbers long long remainder; num1 = llabs(num1); num2 = llabs(num2); // For the purpose of this algorithm, we need to assume that the // first number is the larger of the two if (num1 < num2) { temp = num1; num1 = num2; num2 = temp; } if (num1 + num2 == 0) { (void) fprintf(stderr, "%s(%d): Cannot compute the GCD of two zeros.\n", __FILE__, __LINE__); } if (num1 * num2 == 0) { // One of the numbers was zero. We are done. return num1 + num2; } (void) printf("%lld = (%lld) * (%lld) + %lld\n", num1, num1 / num2, num2, num1 % num2); // Recursively take the GCD of the smaller number and the // remainder of the larger number divided by the smaller number. return get_gcd_euclidean(num2, num1 % num2); } /********************************************************************** * Standard entry point. **********************************************************************/ int main(int argc, char* argv[]) { // The first number parsed from the command line long long num1; // The second number parsed from the command line long long num2; // The GCD of the two numbers long long gcd; if (argc != NUM_ARGS_NEEDED) { (void) fprintf(stderr, "%s(%d): Incorrect number of arguments.\n", __FILE__, __LINE__); exit(EXIT_FAILURE); } errno = 0; num1 = strtoll(argv[1], NULL, 10); if (errno != 0) { perror("The first integer passed in failed to parse"); exit(EXIT_FAILURE); } num2 = strtoll(argv[2], NULL, 10); if (errno != 0) { perror("The second integer passed in failed to parse"); exit(EXIT_FAILURE); } gcd = get_gcd_euclidean(num1, num2); if (gcd != 0) { (void) printf("gcd(%lld, %lld) = %lld\n", num1, num2, gcd); (void) printf("lcm(%lld, %lld) = %lld\n", num1, num2, (num1 / gcd) * num2); } else { (void) printf("Failed to compute gcd(%lld, %lld)\n", num1, num2); exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); return 0; }