Skip to content

Commit

Permalink
v.1.0.0 contd
Browse files Browse the repository at this point in the history
* fix binomial coefficient computation (was inefficient to the point of erroring for large n)
  • Loading branch information
foo123 committed May 3, 2020
1 parent e0e4a58 commit 2ef1d3a
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
21 changes: 17 additions & 4 deletions src/js/Abacus.js
Original file line number Diff line number Diff line change
Expand Up @@ -4218,10 +4218,23 @@ function factorial( n, m )
{
// recursive and memoized
// binomial = C(n,m) = C(n-1,m-1)+C(n-1,m) = n!/m!(n-m)!
res = Arithmetic.isDefault() ? stdMath.round(operate(function(Cnm,i){
// this is faster and will not overflow unnecesarily for default arithmetic
return Cnm*(1+n/i);
}, (n=n-m)+1, null, 2, m)) : add(factorial(sub(n, I), sub(m, I)), factorial(sub(n, I), m))/*div(factorial(n,-m), factorial(m))*/;
if ( Arithmetic.lte(n, 10) )
{
res = add(factorial(sub(n, I), sub(m, I)), factorial(sub(n, I), m));/*div(factorial(n,-m), factorial(m))*/
}
else if ( Arithmetic.isDefault() )
{
res = stdMath.round(operate(function(Cnm,i){
// this is faster and will not overflow unnecesarily for default arithmetic
return Cnm*(1+n/i);
}, (n=n-m)+1, null, 2, m));
}
else
{
i = add(sub(n, m), I); res = i;
while( Arithmetic.lt(i, n) ) { i = add(i, I); res = mul(res, i); }
res = div(res, factorial(m));
}
// memoize only up to MAXMEM results
if ( Arithmetic.lt(n, MAXMEM) )
factorial.mem3[key] = res;
Expand Down
2 changes: 1 addition & 1 deletion src/js/Abacus.min.js

Large diffs are not rendered by default.

0 comments on commit 2ef1d3a

Please sign in to comment.