diff options
author | nobu <nobu@b2dd03c8-39d4-4d8f-98ff-823fe69b080e> | 2007-04-26 08:30:10 +0000 |
---|---|---|
committer | nobu <nobu@b2dd03c8-39d4-4d8f-98ff-823fe69b080e> | 2007-04-26 08:30:10 +0000 |
commit | ab359b8d8c52d007e9ee1deb8a2cf88af4bb3957 (patch) | |
tree | e10bace29abec05970cc226fbe785d91818dc722 /numeric.c | |
parent | 16379460a6b3f11e80519483963be0ffdee9f03a (diff) | |
download | ruby-ab359b8d8c52d007e9ee1deb8a2cf88af4bb3957.tar.gz ruby-ab359b8d8c52d007e9ee1deb8a2cf88af4bb3957.tar.xz ruby-ab359b8d8c52d007e9ee1deb8a2cf88af4bb3957.zip |
* bignum.c (rb_big_pow): reduce multiplying for even number.
* numeric.c (int_pow): calculate power in Fixnum as possible.
[ruby-dev:30726]
git-svn-id: http://svn.ruby-lang.org/repos/ruby/trunk@12223 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
Diffstat (limited to 'numeric.c')
-rw-r--r-- | numeric.c | 34 |
1 files changed, 33 insertions, 1 deletions
@@ -2259,6 +2259,38 @@ fix_divmod(VALUE x, VALUE y) } } +static VALUE +int_pow(long x, unsigned long y) +{ + int neg = x < 0; + long z = 1; + + if (neg) x = -x; + if (y & 1) z = x; + y &= ~1; + do { + while (y % 2 == 0) { + long x2 = x * x; + if (x2 < x || !POSFIXABLE(x2)) { + bignum: + return rb_big_mul(rb_big_pow(rb_int2big(x), LONG2NUM(y)), + rb_int2big(neg ? -z : z)); + } + x = x2; + y >>= 1; + } + { + long xz = x * z; + if (xz < z || xz < x || !POSFIXABLE(xz)) { + goto bignum; + } + z = xz; + } + } while (--y); + if (neg) z = -z; + return LONG2NUM(z); +} + /* * call-seq: * fix ** other => Numeric @@ -2282,7 +2314,7 @@ fix_pow(VALUE x, VALUE y) if (b == 1) return x; a = FIX2LONG(x); if (b > 0) { - return rb_big_pow(rb_int2big(a), y); + return int_pow(a, b); } return rb_float_new(pow((double)a, (double)b)); } |