1 /*
2 * bignum_factorial.c
3 * BigMath
4 *
5 * Created by Curtis Jones on 2008.03.01.
6 * Copyright 2008 __MyCompanyName__. All rights reserved.
7 *
8 */
9
10 #include "bignum.h"
11
12 /**
13 * Calculate num factorial into total and return total.
14 *
15 */
16 bignum_t *
17 bignum_factorial (bignum_t *total, bignum_t *num)
18 {
19 return bignum_factorial_poor(total, num);
20 }
21
22 /**
23 * Poor man's factorial which uses multiplication.
24 *
25 */
26 bignum_t *
27 bignum_factorial_poor (bignum_t *total, bignum_t *num)
28 {
29 bignum_t * tmp1 = bignum_alloc();
30 bignum_t * tmp2 = bignum_alloc();
31
32 __bignum_zero(total);
33
34 bignum_set_bn(total, num);
35 bignum_sub(tmp1, total, bignum_one());
36
37 // while tmp1 > 1
38 // tmp2 = total * tmp1
39 // total = tmp2
40 // tmp2 = tmp1 - 1
41 // tmp1 = tpm2;
42 //
43 while (bignum_gt(tmp1,bignum_one())) {
44 bignum_mul(tmp2, total, tmp1);
45 bignum_set_bn(total, tmp2);
46 bignum_sub(tmp2, tmp1, bignum_one());
47 bignum_set_bn(tmp1, tmp2);
48 }
49
50 if (num->sign == BIGNUM_NEGATIVE)
51 total->sign = BIGNUM_NEGATIVE;
52
53 bignum_free(tmp1);
54 bignum_free(tmp2);
55
56 return total;
57 }
syntax highlighted by Code2HTML, v. 0.9.1