summaryrefslogtreecommitdiff
path: root/nonrecurfact.c
blob: 3fdbf787cd6ebea10e49c5169d78a0367a6d667f (plain)
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
/* non-recursive factorial */
#include <u.h>
#include <libc.h>

void
printdec(int n)
{
	char s[16], *p;
	int r;

	p = s+16;
	*--p = '\n';
	for(;;){
		r = n%10;
		*--p = '0'+r;
		n /= 10;
		if(n == 0 || p == s)
			break;
	}
	write(1, p, s+sizeof(s)-p);
}

int
fact(int n)
{
	int a;

	a = n;
repeat:
	if(n <= 0)
		return 0;
	else if(n == 1)
		return a;
	a *= --n;
	goto repeat;
}

void
usage(void)
{
	fprint(2, "usage: %s n\n", argv0);
	exits("usage");
}

void
main(int argc, char *argv[])
{
	int n;

	ARGBEGIN{
	default: usage();
	}ARGEND;
	if(argc != 1)
		usage();
	n = strtol(argv[0], nil, 0);
	printdec(fact(n));
	exits(0);
}