Class: Fixnum

Inherits:
Object show all
Defined in:
(unknown)

Instance Method Summary collapse

Instance Method Details

#factObject

x! ( specially for /c/ ^__^ ) 5.fact # => 120 x3 boost relative to 1.8.7



415
416
417
418
419
420
421
422
423
# File 'ext/rmtools.cpp', line 415

static VALUE rb_math_factorial(VALUE x)
{
  long a = FIX2LONG(x);
  for (int i = 2; i < a; i++) 
    x = TYPE(x) == T_BIGNUM ? 
      rb_big_mul(x, rb_int2big(i)) : 
      rb_big_mul(rb_int2big(FIX2LONG(x)), rb_int2big(i));
  return x;
}

#factorizeObject

timer(100000) Fixnum.10737418231073741823.factorize

> “res: [3, 3, 7, 11, 31, 151, 331], one: 0.0053ms, total: 530.0ms”

ruby count Bignums starting from 2**30 < 2**30: x1-x30 speed, >= 2**30: x1 - x3 speed ~_~ Caution! It can just hung up on numbers over 2**64 and you’ll have to kill it -9 And this shit doesn’t think if you have 64-bit system, so it could be faster a bit



443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
# File 'ext/rmtools.cpp', line 443

static VALUE rb_math_factorization(VALUE x) {
  VALUE factors = rb_ary_new2(31);
  int len = 0;
  long y = FIX2LONG(x);
  long n = 2;
  while (n*n <= y) {
      if (y%n == 0) {
          y /= n;
          rb_ary_store(factors, len++, LONG2FIX(n));
      } else
          n++;
  }
  rb_ary_store(factors, len++, LONG2FIX(y));
  ARY_SET_LEN(factors, len);
  return factors;
}