Skip to content

Instantly share code, notes, and snippets.

@mundry
Last active August 29, 2015 14:07
Show Gist options
  • Save mundry/e92ce312313de9b4eaad to your computer and use it in GitHub Desktop.
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.
#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