Last active
August 29, 2015 14:07
-
-
Save mundry/e92ce312313de9b4eaad to your computer and use it in GitHub Desktop.
A C program to calculate the greatest common divisor of two numbers using the Euclidean algorithm.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <inttypes.h> | |
int gcd(int a, int b) { | |
return b == 0 ? a : gcd(b, a - (((int) (a / b)) * b)); | |
} | |
int main(int argc, char const *argv[]) { | |
if (argc >= 3) { | |
const unsigned short pairs = (argc - 1) / 2; | |
int valueA, valueB, a, b, tmp; | |
for (int i = 0; i < pairs; i++) { | |
a = valueA = (int) strtoimax(argv[i * 2 + 1], NULL, 10); | |
b = valueB = (int) strtoimax(argv[i * 2 + 2], NULL, 10); | |
while (b != 0) { | |
tmp = b; | |
b = a - (((int) (a / b)) * b); | |
a = tmp; | |
} | |
printf("gcd(%d, %d) = %d\n", valueA, valueB, a); | |
printf("gcd(%d, %d) = %d\n", valueA, valueB, gcd(valueA, valueB)); | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment