|
1 /* |
|
2 * gcd.c |
|
3 * |
|
4 * Greatest common divisor |
|
5 * |
|
6 * This Source Code Form is subject to the terms of the Mozilla Public |
|
7 * License, v. 2.0. If a copy of the MPL was not distributed with this |
|
8 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
|
9 |
|
10 #include <stdio.h> |
|
11 #include <stdlib.h> |
|
12 #include <string.h> |
|
13 |
|
14 #include "mpi.h" |
|
15 |
|
16 char *g_prog = NULL; |
|
17 |
|
18 void print_mp_int(mp_int *mp, FILE *ofp); |
|
19 |
|
20 int main(int argc, char *argv[]) |
|
21 { |
|
22 mp_int a, b, x, y; |
|
23 mp_err res; |
|
24 int ext = 0; |
|
25 |
|
26 g_prog = argv[0]; |
|
27 |
|
28 if(argc < 3) { |
|
29 fprintf(stderr, "Usage: %s <a> <b>\n", g_prog); |
|
30 return 1; |
|
31 } |
|
32 |
|
33 mp_init(&a); mp_read_radix(&a, argv[1], 10); |
|
34 mp_init(&b); mp_read_radix(&b, argv[2], 10); |
|
35 |
|
36 /* If we were called 'xgcd', compute x, y so that g = ax + by */ |
|
37 if(strcmp(g_prog, "xgcd") == 0) { |
|
38 ext = 1; |
|
39 mp_init(&x); mp_init(&y); |
|
40 } |
|
41 |
|
42 if(ext) { |
|
43 if((res = mp_xgcd(&a, &b, &a, &x, &y)) != MP_OKAY) { |
|
44 fprintf(stderr, "%s: error: %s\n", g_prog, mp_strerror(res)); |
|
45 mp_clear(&a); mp_clear(&b); |
|
46 mp_clear(&x); mp_clear(&y); |
|
47 return 1; |
|
48 } |
|
49 } else { |
|
50 if((res = mp_gcd(&a, &b, &a)) != MP_OKAY) { |
|
51 fprintf(stderr, "%s: error: %s\n", g_prog, |
|
52 mp_strerror(res)); |
|
53 mp_clear(&a); mp_clear(&b); |
|
54 return 1; |
|
55 } |
|
56 } |
|
57 |
|
58 print_mp_int(&a, stdout); |
|
59 if(ext) { |
|
60 fputs("x = ", stdout); print_mp_int(&x, stdout); |
|
61 fputs("y = ", stdout); print_mp_int(&y, stdout); |
|
62 } |
|
63 |
|
64 mp_clear(&a); mp_clear(&b); |
|
65 |
|
66 if(ext) { |
|
67 mp_clear(&x); |
|
68 mp_clear(&y); |
|
69 } |
|
70 |
|
71 return 0; |
|
72 |
|
73 } |
|
74 |
|
75 void print_mp_int(mp_int *mp, FILE *ofp) |
|
76 { |
|
77 char *buf; |
|
78 int len; |
|
79 |
|
80 len = mp_radix_size(mp, 10); |
|
81 buf = calloc(len, sizeof(char)); |
|
82 mp_todecimal(mp, buf); |
|
83 fprintf(ofp, "%s\n", buf); |
|
84 free(buf); |
|
85 |
|
86 } |