File: factorial.5c

package info (click to toggle)
nickle 2.107
  • links: PTS
  • area: main
  • in suites: forky, sid
  • size: 3,756 kB
  • sloc: ansic: 27,954; yacc: 1,874; lex: 954; sh: 204; makefile: 13; lisp: 1
file content (61 lines) | stat: -rw-r--r-- 943 bytes parent folder | download | duplicates (9)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
 * Nickle test suite
 *
 * factorial tests
 */

int errors = 0;

int fact(int n) {
    int r = 1;
    while (n > 1) {
    	r *= n;
	n--;
    }
    return r;
}

void check_factorial(int max) {
     for (int n = 0; n < max; n++) {
	 int is = n!;
     	 int should = fact(n);

     	 if (is != should) {
	    printf ("check failed %d! (was %d should be %d)\n",
	    	    n, is, should);
	    ++errors;
	 }
     }
}

real stirling (real n)
{
    n = imprecise (n);
    return sqrt (2 * pi * n) * (n / Math::e) ** n;
}

void check_one_stirling(int v) {
	real s = stirling(v);
	real f = v!;
	real r = f/s;
	real e = 0.1/v;
	if (r < 1 || r > (1 + e)) {
		printf("check failed %d! (was %d should be close to %g)\n",
		       v, f, s);
		++errors;
	}
}

void check_stirling(int rep) {
	real v = 13;
	while (rep-- > 0) {
		int iv = floor(v);
		check_one_stirling(iv);
		v = v * 3 + 2;
	}
}

check_stirling(10);
check_factorial(1000);

exit (errors);