From: Christoph Date: 2002-04-06T02:54:34+09:00 Subject: Re: Fibonacci Number Generators wrote in .... > Here I show some examples inadequate for newbie's question :-) > > 1. The parallel assignment makes an Array object, so it costs > a little. It may be better to avoid that and use the temporary > variable which belongs to the outside of the iterator block: > > def fib2(n) > return n if n < 2 > f1, f2 = 0, 1 > tmp = nil > (n-1).times { > tmp = f1; f1 = f2; f2 += tmp # swap > } > f2 > end > > This resembles the original fib(n) as a result. > > 2. If you want to calculate fib(n) repeatedly, cashing the > intermediate results is advantageous: > > def (Fib = [0, 1]).[](n) > super || Fib[n] = Fib[n-1] + Fib[n-2] > end > You can also combine 1 & 2 (this avoids the unnecessary recursive super call's) ---- Fib = [0,1] def Fib.[](n) super || ( for i in length..n do self[i] = super(i-1)+super(i-2) end super) end ---- /Christoph