|
1 /* |
|
2 * fact.c |
|
3 * |
|
4 * Compute factorial of input integer |
|
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 mp_err mp_fact(mp_int *a, mp_int *b); |
|
17 |
|
18 int main(int argc, char *argv[]) |
|
19 { |
|
20 mp_int a; |
|
21 mp_err res; |
|
22 |
|
23 if(argc < 2) { |
|
24 fprintf(stderr, "Usage: %s <number>\n", argv[0]); |
|
25 return 1; |
|
26 } |
|
27 |
|
28 mp_init(&a); |
|
29 mp_read_radix(&a, argv[1], 10); |
|
30 |
|
31 if((res = mp_fact(&a, &a)) != MP_OKAY) { |
|
32 fprintf(stderr, "%s: error: %s\n", argv[0], |
|
33 mp_strerror(res)); |
|
34 mp_clear(&a); |
|
35 return 1; |
|
36 } |
|
37 |
|
38 { |
|
39 char *buf; |
|
40 int len; |
|
41 |
|
42 len = mp_radix_size(&a, 10); |
|
43 buf = malloc(len); |
|
44 mp_todecimal(&a, buf); |
|
45 |
|
46 puts(buf); |
|
47 |
|
48 free(buf); |
|
49 } |
|
50 |
|
51 mp_clear(&a); |
|
52 return 0; |
|
53 } |
|
54 |
|
55 mp_err mp_fact(mp_int *a, mp_int *b) |
|
56 { |
|
57 mp_int ix, s; |
|
58 mp_err res = MP_OKAY; |
|
59 |
|
60 if(mp_cmp_z(a) < 0) |
|
61 return MP_UNDEF; |
|
62 |
|
63 mp_init(&s); |
|
64 mp_add_d(&s, 1, &s); /* s = 1 */ |
|
65 mp_init(&ix); |
|
66 mp_add_d(&ix, 1, &ix); /* ix = 1 */ |
|
67 |
|
68 for(/* */; mp_cmp(&ix, a) <= 0; mp_add_d(&ix, 1, &ix)) { |
|
69 if((res = mp_mul(&s, &ix, &s)) != MP_OKAY) |
|
70 break; |
|
71 } |
|
72 |
|
73 mp_clear(&ix); |
|
74 |
|
75 /* Copy out results if we got them */ |
|
76 if(res == MP_OKAY) |
|
77 mp_copy(&s, b); |
|
78 |
|
79 mp_clear(&s); |
|
80 |
|
81 return res; |
|
82 } |