michael@0: /* michael@0: * fact.c michael@0: * michael@0: * Compute factorial of input integer 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: mp_err mp_fact(mp_int *a, mp_int *b); michael@0: michael@0: int main(int argc, char *argv[]) michael@0: { michael@0: mp_int a; michael@0: mp_err res; michael@0: michael@0: if(argc < 2) { michael@0: fprintf(stderr, "Usage: %s \n", argv[0]); michael@0: return 1; michael@0: } michael@0: michael@0: mp_init(&a); michael@0: mp_read_radix(&a, argv[1], 10); michael@0: michael@0: if((res = mp_fact(&a, &a)) != MP_OKAY) { michael@0: fprintf(stderr, "%s: error: %s\n", argv[0], michael@0: mp_strerror(res)); michael@0: mp_clear(&a); michael@0: return 1; michael@0: } michael@0: michael@0: { michael@0: char *buf; michael@0: int len; michael@0: michael@0: len = mp_radix_size(&a, 10); michael@0: buf = malloc(len); michael@0: mp_todecimal(&a, buf); michael@0: michael@0: puts(buf); michael@0: michael@0: free(buf); michael@0: } michael@0: michael@0: mp_clear(&a); michael@0: return 0; michael@0: } michael@0: michael@0: mp_err mp_fact(mp_int *a, mp_int *b) michael@0: { michael@0: mp_int ix, s; michael@0: mp_err res = MP_OKAY; michael@0: michael@0: if(mp_cmp_z(a) < 0) michael@0: return MP_UNDEF; michael@0: michael@0: mp_init(&s); michael@0: mp_add_d(&s, 1, &s); /* s = 1 */ michael@0: mp_init(&ix); michael@0: mp_add_d(&ix, 1, &ix); /* ix = 1 */ michael@0: michael@0: for(/* */; mp_cmp(&ix, a) <= 0; mp_add_d(&ix, 1, &ix)) { michael@0: if((res = mp_mul(&s, &ix, &s)) != MP_OKAY) michael@0: break; michael@0: } michael@0: michael@0: mp_clear(&ix); michael@0: michael@0: /* Copy out results if we got them */ michael@0: if(res == MP_OKAY) michael@0: mp_copy(&s, b); michael@0: michael@0: mp_clear(&s); michael@0: michael@0: return res; michael@0: }