1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/security/nss/lib/freebl/mpi/utils/fact.c Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,82 @@ 1.4 +/* 1.5 + * fact.c 1.6 + * 1.7 + * Compute factorial of input integer 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 +mp_err mp_fact(mp_int *a, mp_int *b); 1.20 + 1.21 +int main(int argc, char *argv[]) 1.22 +{ 1.23 + mp_int a; 1.24 + mp_err res; 1.25 + 1.26 + if(argc < 2) { 1.27 + fprintf(stderr, "Usage: %s <number>\n", argv[0]); 1.28 + return 1; 1.29 + } 1.30 + 1.31 + mp_init(&a); 1.32 + mp_read_radix(&a, argv[1], 10); 1.33 + 1.34 + if((res = mp_fact(&a, &a)) != MP_OKAY) { 1.35 + fprintf(stderr, "%s: error: %s\n", argv[0], 1.36 + mp_strerror(res)); 1.37 + mp_clear(&a); 1.38 + return 1; 1.39 + } 1.40 + 1.41 + { 1.42 + char *buf; 1.43 + int len; 1.44 + 1.45 + len = mp_radix_size(&a, 10); 1.46 + buf = malloc(len); 1.47 + mp_todecimal(&a, buf); 1.48 + 1.49 + puts(buf); 1.50 + 1.51 + free(buf); 1.52 + } 1.53 + 1.54 + mp_clear(&a); 1.55 + return 0; 1.56 +} 1.57 + 1.58 +mp_err mp_fact(mp_int *a, mp_int *b) 1.59 +{ 1.60 + mp_int ix, s; 1.61 + mp_err res = MP_OKAY; 1.62 + 1.63 + if(mp_cmp_z(a) < 0) 1.64 + return MP_UNDEF; 1.65 + 1.66 + mp_init(&s); 1.67 + mp_add_d(&s, 1, &s); /* s = 1 */ 1.68 + mp_init(&ix); 1.69 + mp_add_d(&ix, 1, &ix); /* ix = 1 */ 1.70 + 1.71 + for(/* */; mp_cmp(&ix, a) <= 0; mp_add_d(&ix, 1, &ix)) { 1.72 + if((res = mp_mul(&s, &ix, &s)) != MP_OKAY) 1.73 + break; 1.74 + } 1.75 + 1.76 + mp_clear(&ix); 1.77 + 1.78 + /* Copy out results if we got them */ 1.79 + if(res == MP_OKAY) 1.80 + mp_copy(&s, b); 1.81 + 1.82 + mp_clear(&s); 1.83 + 1.84 + return res; 1.85 +}