1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/security/nss/lib/freebl/mpi/utils/gcd.c Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,86 @@ 1.4 +/* 1.5 + * gcd.c 1.6 + * 1.7 + * Greatest common divisor 1.8 + * 1.9 + * This Source Code Form is subject to the terms of the Mozilla Public 1.10 + * License, v. 2.0. If a copy of the MPL was not distributed with this 1.11 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 1.12 + 1.13 +#include <stdio.h> 1.14 +#include <stdlib.h> 1.15 +#include <string.h> 1.16 + 1.17 +#include "mpi.h" 1.18 + 1.19 +char *g_prog = NULL; 1.20 + 1.21 +void print_mp_int(mp_int *mp, FILE *ofp); 1.22 + 1.23 +int main(int argc, char *argv[]) 1.24 +{ 1.25 + mp_int a, b, x, y; 1.26 + mp_err res; 1.27 + int ext = 0; 1.28 + 1.29 + g_prog = argv[0]; 1.30 + 1.31 + if(argc < 3) { 1.32 + fprintf(stderr, "Usage: %s <a> <b>\n", g_prog); 1.33 + return 1; 1.34 + } 1.35 + 1.36 + mp_init(&a); mp_read_radix(&a, argv[1], 10); 1.37 + mp_init(&b); mp_read_radix(&b, argv[2], 10); 1.38 + 1.39 + /* If we were called 'xgcd', compute x, y so that g = ax + by */ 1.40 + if(strcmp(g_prog, "xgcd") == 0) { 1.41 + ext = 1; 1.42 + mp_init(&x); mp_init(&y); 1.43 + } 1.44 + 1.45 + if(ext) { 1.46 + if((res = mp_xgcd(&a, &b, &a, &x, &y)) != MP_OKAY) { 1.47 + fprintf(stderr, "%s: error: %s\n", g_prog, mp_strerror(res)); 1.48 + mp_clear(&a); mp_clear(&b); 1.49 + mp_clear(&x); mp_clear(&y); 1.50 + return 1; 1.51 + } 1.52 + } else { 1.53 + if((res = mp_gcd(&a, &b, &a)) != MP_OKAY) { 1.54 + fprintf(stderr, "%s: error: %s\n", g_prog, 1.55 + mp_strerror(res)); 1.56 + mp_clear(&a); mp_clear(&b); 1.57 + return 1; 1.58 + } 1.59 + } 1.60 + 1.61 + print_mp_int(&a, stdout); 1.62 + if(ext) { 1.63 + fputs("x = ", stdout); print_mp_int(&x, stdout); 1.64 + fputs("y = ", stdout); print_mp_int(&y, stdout); 1.65 + } 1.66 + 1.67 + mp_clear(&a); mp_clear(&b); 1.68 + 1.69 + if(ext) { 1.70 + mp_clear(&x); 1.71 + mp_clear(&y); 1.72 + } 1.73 + 1.74 + return 0; 1.75 + 1.76 +} 1.77 + 1.78 +void print_mp_int(mp_int *mp, FILE *ofp) 1.79 +{ 1.80 + char *buf; 1.81 + int len; 1.82 + 1.83 + len = mp_radix_size(mp, 10); 1.84 + buf = calloc(len, sizeof(char)); 1.85 + mp_todecimal(mp, buf); 1.86 + fprintf(ofp, "%s\n", buf); 1.87 + free(buf); 1.88 + 1.89 +}