1
0
Fork 0
mirror of https://github.com/ruby/ruby.git synced 2022-11-09 12:17:21 -05:00

array.c: refine binomial_coefficient

* array.c (binomial_coefficient): get rid of bignums by division
  after each multiplications.

git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@59692 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
This commit is contained in:
nobu 2017-08-30 08:26:16 +00:00
parent 96223329d0
commit f0ae63b072

15
array.c
View file

@ -5096,16 +5096,23 @@ descending_factorial(long from, long how_many)
static VALUE static VALUE
binomial_coefficient(long comb, long size) binomial_coefficient(long comb, long size)
{ {
VALUE r, v; VALUE r;
long i;
if (comb > size-comb) { if (comb > size-comb) {
comb = size-comb; comb = size-comb;
} }
if (comb < 0) { if (comb < 0) {
return LONG2FIX(0); return LONG2FIX(0);
} }
r = descending_factorial(size, comb); else if (comb == 0) {
v = descending_factorial(comb, comb); return LONG2FIX(1);
return rb_int_idiv(r, v); }
r = LONG2FIX(size);
for (i = 1; i < comb; ++i) {
r = rb_int_mul(r, LONG2FIX(size - i));
r = rb_int_idiv(r, LONG2FIX(i + 1));
}
return r;
} }
static VALUE static VALUE