summaryrefslogtreecommitdiff
path: root/bincoeff.c
blob: 624bb19a79833a462f3ecc275379555f79c2e91e (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
59
60
61
62
63
#include <u.h>
#include <libc.h>

vlong t0, Δt;

double
fac(double n)
{
	double Π;

	Π = 1;
	assert(n > 0);
	while(n > 1)
		Π *= n--;
	return Π;
}

double
bincoeff(double n, double k)
{
	assert(k <= n);
	return fac(n)/(fac(k)*fac(n-k));
}

double
bincoeffmul(double n, double k)
{
	double Π;
	int i;

	assert(k <= n);
	Π = 1;
	for(i = 1; i <= k; i++)
		Π *= (n + 1 - i)/i;
	return Π;
}

void
usage(void)
{
	fprint(2, "usage: bincoeff n k\n");
	exits("usage");
}

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

	if(argc != 3)
		usage();
	n = strtod(argv[1], nil);
	k = strtod(argv[2], nil);
	t0 = nsec();
	bc = bincoeff(n, k);
	Δt = nsec()-t0;
	print("method 1: %g (%lldns)\n", bc, Δt);
	t0 = nsec();
	bc = bincoeffmul(n, k);
	Δt = nsec()-t0;
	print("method 2: %g (%lldns)\n", bc, Δt);
	exits(nil);
}