Skip to content

Commit 2ef1d3a

Browse files
committed
v.1.0.0 contd
* fix binomial coefficient computation (was inefficient to the point of erroring for large n)
1 parent e0e4a58 commit 2ef1d3a

File tree

2 files changed

+18
-5
lines changed

2 files changed

+18
-5
lines changed

src/js/Abacus.js

+17-4
Original file line numberDiff line numberDiff line change
@@ -4218,10 +4218,23 @@ function factorial( n, m )
42184218
{
42194219
// recursive and memoized
42204220
// binomial = C(n,m) = C(n-1,m-1)+C(n-1,m) = n!/m!(n-m)!
4221-
res = Arithmetic.isDefault() ? stdMath.round(operate(function(Cnm,i){
4222-
// this is faster and will not overflow unnecesarily for default arithmetic
4223-
return Cnm*(1+n/i);
4224-
}, (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))*/;
4221+
if ( Arithmetic.lte(n, 10) )
4222+
{
4223+
res = add(factorial(sub(n, I), sub(m, I)), factorial(sub(n, I), m));/*div(factorial(n,-m), factorial(m))*/
4224+
}
4225+
else if ( Arithmetic.isDefault() )
4226+
{
4227+
res = stdMath.round(operate(function(Cnm,i){
4228+
// this is faster and will not overflow unnecesarily for default arithmetic
4229+
return Cnm*(1+n/i);
4230+
}, (n=n-m)+1, null, 2, m));
4231+
}
4232+
else
4233+
{
4234+
i = add(sub(n, m), I); res = i;
4235+
while( Arithmetic.lt(i, n) ) { i = add(i, I); res = mul(res, i); }
4236+
res = div(res, factorial(m));
4237+
}
42254238
// memoize only up to MAXMEM results
42264239
if ( Arithmetic.lt(n, MAXMEM) )
42274240
factorial.mem3[key] = res;

src/js/Abacus.min.js

+1-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)