Permalink
Browse files

multiplicative algorithm is pretty fast, pascal triangle example

  • Loading branch information...
0 parents commit 429ebfe9e909392ef1c41b762162ec822d487ded @substack committed Aug 13, 2012
Showing with 21 additions and 0 deletions.
  1. +10 −0 example/pascal.js
  2. +11 −0 index.js
@@ -0,0 +1,10 @@
+var choose = require('../');
+
+var rows = 15;
+for (var n = 0; n < rows; n++) {
+ var row = [];
+ for (var k = 0; k <= n; k++) {
+ row.push(choose(n, k));
+ }
+ console.dir(row);
+}
@@ -0,0 +1,11 @@
+// transliterated from: https://en.wikipedia.org/wiki/Binomial_coefficient#Binomial_coefficient_in_programming_languages
+
+module.exports = function (n, k) {
+ if (k < 0 || k > n) return 0;
+ if (k > n - k) k = n - k;
+ var res = 1;
+ for (var i = 0; i < k; i++) {
+ res *= (n - k + i + 1) / (i + 1);
+ }
+ return Math.round(res);
+};

0 comments on commit 429ebfe

Please sign in to comment.