From: ara.t.howard@... Date: 2007-04-17T23:44:13+09:00 Subject: Re: factorial in ruby On Tue, 17 Apr 2007, Florian Frank wrote: > ara.t.howard@noaa.gov wrote: >> not the integer wrap from the c version - this is a case where c gets you >> crap >> answers real quick. you need more that just c, but also an arbitrary >> precision >> arithmitic library to do factorial fast. > > Caching can avoid unnecessary multiplications (while using Bignums), if one > wants to compute a lot of factorials: > > module Factorial > module_function > > @@cache = [ 1 ] > > def fact(n) > raise ArgumentError, "n has to be >= 0" if n < 0 > @@cache.size.upto(n) { |i| @@cache[i] = i * @@cache[i - 1] } > @@cache[n] > end > end > > if $0 == __FILE__ > require 'test/unit' > class TestFactorial < Test::Unit::TestCase > include Factorial > def test_fact > assert_raises(ArgumentError) { fact(-1) } > assert_equal 1, fact(0) > assert_equal 1, fact(1) > assert_equal 2, fact(2) > assert_equal 6, fact(3) > assert_equal 24, fact(4) > assert_equal 120, fact(5) > assert_equal 3628800, fact(10) > end > end > end > > This should get faster, the more factorials you want to compute. and even more reason to delay writing it in c. my main point was simply that almost no function is straight forward to write in c if one is looking for robust code. also, because ruby is fast enough for small values but c is wrong for even medium values it begs the question of whether writing a seemingly simply function like factorial in c really would be worth the work. maybe someone can hack a rubyinline version using bignums so we can compare that? kind regards. -a -- be kind whenever possible... it is always possible. - the dalai lama