Wed, 31 Dec 2014 06:09:35 +0100
Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.
michael@0 | 1 | /* |
michael@0 | 2 | * fact.c |
michael@0 | 3 | * |
michael@0 | 4 | * Compute factorial of input integer |
michael@0 | 5 | * |
michael@0 | 6 | * This Source Code Form is subject to the terms of the Mozilla Public |
michael@0 | 7 | * License, v. 2.0. If a copy of the MPL was not distributed with this |
michael@0 | 8 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
michael@0 | 9 | |
michael@0 | 10 | #include <stdio.h> |
michael@0 | 11 | #include <stdlib.h> |
michael@0 | 12 | #include <string.h> |
michael@0 | 13 | |
michael@0 | 14 | #include "mpi.h" |
michael@0 | 15 | |
michael@0 | 16 | mp_err mp_fact(mp_int *a, mp_int *b); |
michael@0 | 17 | |
michael@0 | 18 | int main(int argc, char *argv[]) |
michael@0 | 19 | { |
michael@0 | 20 | mp_int a; |
michael@0 | 21 | mp_err res; |
michael@0 | 22 | |
michael@0 | 23 | if(argc < 2) { |
michael@0 | 24 | fprintf(stderr, "Usage: %s <number>\n", argv[0]); |
michael@0 | 25 | return 1; |
michael@0 | 26 | } |
michael@0 | 27 | |
michael@0 | 28 | mp_init(&a); |
michael@0 | 29 | mp_read_radix(&a, argv[1], 10); |
michael@0 | 30 | |
michael@0 | 31 | if((res = mp_fact(&a, &a)) != MP_OKAY) { |
michael@0 | 32 | fprintf(stderr, "%s: error: %s\n", argv[0], |
michael@0 | 33 | mp_strerror(res)); |
michael@0 | 34 | mp_clear(&a); |
michael@0 | 35 | return 1; |
michael@0 | 36 | } |
michael@0 | 37 | |
michael@0 | 38 | { |
michael@0 | 39 | char *buf; |
michael@0 | 40 | int len; |
michael@0 | 41 | |
michael@0 | 42 | len = mp_radix_size(&a, 10); |
michael@0 | 43 | buf = malloc(len); |
michael@0 | 44 | mp_todecimal(&a, buf); |
michael@0 | 45 | |
michael@0 | 46 | puts(buf); |
michael@0 | 47 | |
michael@0 | 48 | free(buf); |
michael@0 | 49 | } |
michael@0 | 50 | |
michael@0 | 51 | mp_clear(&a); |
michael@0 | 52 | return 0; |
michael@0 | 53 | } |
michael@0 | 54 | |
michael@0 | 55 | mp_err mp_fact(mp_int *a, mp_int *b) |
michael@0 | 56 | { |
michael@0 | 57 | mp_int ix, s; |
michael@0 | 58 | mp_err res = MP_OKAY; |
michael@0 | 59 | |
michael@0 | 60 | if(mp_cmp_z(a) < 0) |
michael@0 | 61 | return MP_UNDEF; |
michael@0 | 62 | |
michael@0 | 63 | mp_init(&s); |
michael@0 | 64 | mp_add_d(&s, 1, &s); /* s = 1 */ |
michael@0 | 65 | mp_init(&ix); |
michael@0 | 66 | mp_add_d(&ix, 1, &ix); /* ix = 1 */ |
michael@0 | 67 | |
michael@0 | 68 | for(/* */; mp_cmp(&ix, a) <= 0; mp_add_d(&ix, 1, &ix)) { |
michael@0 | 69 | if((res = mp_mul(&s, &ix, &s)) != MP_OKAY) |
michael@0 | 70 | break; |
michael@0 | 71 | } |
michael@0 | 72 | |
michael@0 | 73 | mp_clear(&ix); |
michael@0 | 74 | |
michael@0 | 75 | /* Copy out results if we got them */ |
michael@0 | 76 | if(res == MP_OKAY) |
michael@0 | 77 | mp_copy(&s, b); |
michael@0 | 78 | |
michael@0 | 79 | mp_clear(&s); |
michael@0 | 80 | |
michael@0 | 81 | return res; |
michael@0 | 82 | } |