diff options
author | rodri <rgl@antares-labs.eu> | 2020-02-22 09:56:09 +0000 |
---|---|---|
committer | rodri <rgl@antares-labs.eu> | 2020-02-22 09:56:09 +0000 |
commit | a39951d8f69209cfea2b7051832b851914e662ef (patch) | |
tree | e4cd1c32e5d6f531b523f6fda558cc3a5f603547 /bincoeff.c | |
download | brokentoys-a39951d8f69209cfea2b7051832b851914e662ef.tar.gz brokentoys-a39951d8f69209cfea2b7051832b851914e662ef.tar.bz2 brokentoys-a39951d8f69209cfea2b7051832b851914e662ef.zip |
now version controlled.
Diffstat (limited to 'bincoeff.c')
-rw-r--r-- | bincoeff.c | 63 |
1 files changed, 63 insertions, 0 deletions
diff --git a/bincoeff.c b/bincoeff.c new file mode 100644 index 0000000..624bb19 --- /dev/null +++ b/bincoeff.c @@ -0,0 +1,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); +} |