michael@0: /* michael@0: * gcd.c michael@0: * michael@0: * Greatest common divisor michael@0: * michael@0: * This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: #include michael@0: #include michael@0: #include michael@0: michael@0: #include "mpi.h" michael@0: michael@0: char *g_prog = NULL; michael@0: michael@0: void print_mp_int(mp_int *mp, FILE *ofp); michael@0: michael@0: int main(int argc, char *argv[]) michael@0: { michael@0: mp_int a, b, x, y; michael@0: mp_err res; michael@0: int ext = 0; michael@0: michael@0: g_prog = argv[0]; michael@0: michael@0: if(argc < 3) { michael@0: fprintf(stderr, "Usage: %s \n", g_prog); michael@0: return 1; michael@0: } michael@0: michael@0: mp_init(&a); mp_read_radix(&a, argv[1], 10); michael@0: mp_init(&b); mp_read_radix(&b, argv[2], 10); michael@0: michael@0: /* If we were called 'xgcd', compute x, y so that g = ax + by */ michael@0: if(strcmp(g_prog, "xgcd") == 0) { michael@0: ext = 1; michael@0: mp_init(&x); mp_init(&y); michael@0: } michael@0: michael@0: if(ext) { michael@0: if((res = mp_xgcd(&a, &b, &a, &x, &y)) != MP_OKAY) { michael@0: fprintf(stderr, "%s: error: %s\n", g_prog, mp_strerror(res)); michael@0: mp_clear(&a); mp_clear(&b); michael@0: mp_clear(&x); mp_clear(&y); michael@0: return 1; michael@0: } michael@0: } else { michael@0: if((res = mp_gcd(&a, &b, &a)) != MP_OKAY) { michael@0: fprintf(stderr, "%s: error: %s\n", g_prog, michael@0: mp_strerror(res)); michael@0: mp_clear(&a); mp_clear(&b); michael@0: return 1; michael@0: } michael@0: } michael@0: michael@0: print_mp_int(&a, stdout); michael@0: if(ext) { michael@0: fputs("x = ", stdout); print_mp_int(&x, stdout); michael@0: fputs("y = ", stdout); print_mp_int(&y, stdout); michael@0: } michael@0: michael@0: mp_clear(&a); mp_clear(&b); michael@0: michael@0: if(ext) { michael@0: mp_clear(&x); michael@0: mp_clear(&y); michael@0: } michael@0: michael@0: return 0; michael@0: michael@0: } michael@0: michael@0: void print_mp_int(mp_int *mp, FILE *ofp) michael@0: { michael@0: char *buf; michael@0: int len; michael@0: michael@0: len = mp_radix_size(mp, 10); michael@0: buf = calloc(len, sizeof(char)); michael@0: mp_todecimal(mp, buf); michael@0: fprintf(ofp, "%s\n", buf); michael@0: free(buf); michael@0: michael@0: }