From: Florian Frank Date: 2007-04-17T19:32:26+09:00 Subject: Re: factorial in ruby 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. -- Florian Frank