From: C Erler Date: 2006-05-27T08:13:37+09:00 Subject: Fast Fibonacci method ------=_Part_45491_13952781.1148685214535 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: quoted-printable Content-Disposition: inline The fastest pure-Ruby Fibonacci method I have been able to come up with is = a copy of the GMP algorithm described at http://www.swox.com/gmp/manual/Fibonacci-Numbers-Algorithm.html Is there a Ruby implementation that gets better time results for the millionth Fibonacci number (timing code included at bottom) ? class Integer FibonacciCache =3D Hash.new do |hash, key| subkey =3D key.div(2) case key.modulo(4) when 1 hash[key] =3D (2*hash[subkey] + hash[subkey - 1])*(2*hash[subkey] - hash[subkey - 1]) + 2 when 3 hash[key] =3D (2*hash[subkey] + hash[subkey - 1])*(2*hash[subkey] - hash[subkey - 1]) - 2 else hash[key] =3D hash[subkey] * (hash[subkey] + 2*hash[subkey - 1]) end end FibonacciCache[0] =3D 0 FibonacciCache[1] =3D 1 def fib return FibonacciCache[self] end def fib_uncached return FibonacciCache.dup[self] end end start_time =3D Time.now 1_000_000.fib p Time.now - start_time puts "Doesn't work !" unless (1..10).map { |i| i.fib } =3D=3D [1, 1, 2, 3, = 5, 8, 13, 21, 34, 55] ------=_Part_45491_13952781.1148685214535--