Greatest common divisor
Small C code that get greatest common divisor for two given ints
#include <stdlib.h> #include <stdio.h> #include <errno.h> /* (c) by Taatudi */ int main(int argc, char **argv) { unsigned t1 = 0, t2 = 0, a = 0, b = 0, m = 0; if (argc < 3) { printf("Usage: %s <int> <int>\n", argv[0] ? argv[0] : "gcd"); exit(EXIT_FAILURE); } errno = 0; t1 = strtoul(argv[1], NULL, 10); t2 = strtoul(argv[2], NULL, 10); if (t1 == 0 || t2 == 0) { printf("Input args must be integer numbers and != 0!\n"); exit(EXIT_FAILURE); } if (errno == EINVAL) { printf("No conversion could be performed!\n"); exit(EXIT_FAILURE); } if (errno == ERANGE) { printf("Number you entered is too long!\n"); exit(EXIT_FAILURE); } if (t1 > t2) { a = t1; b = t2; } else { a = t2; b = t1; } m = a % b; while (m != 0) { a = b; b = m; m = a % b; } printf("Greatest common divisor: %u\n", b); exit(EXIT_SUCCESS); }

This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
Download this code in plain text format here