Ruby beats them all

Matt O’Connor wrote:

n < 1 ? val : fib_helper( n-1, next_val + val, next_val)
n < 1 ? val : fib_helper( n-1, next_val + val, next_val)
end
fib_helper( n, 1, 1)
end

An alternative implementation might even use only one subroutine.

def fib n, p1 =1, p2 =1
n < 1 ? p2 : fib( n - 1, p1 + p2, p1 )
end

On Dec 15, 2005, at 8:46 PM, Matt O’Connor wrote:

the above code (in accumulator-passing style) only works through
end

Matt

Sadly, that doesn’t really hide the helper function. fib_helper will
be at the same scope as fib, Ruby doesn’t currently do nested
function definitions.

i’m sorry for reviving an old topic, but hows this:

def fib(n)
list=[0,1]
2.upto(n-1) do |s|
list << (list[s-2]+list[s-1])
end
list
end

greetings, Dirk.

On 15 Dec 2005 07:17:22 -0800, in comp.lang.ruby , “jwesley”
[email protected] in
[email protected] wrote:

the above code (in accumulator-passing style) only works through about
n=1300 for me.

It is grossly inefficient to implement fib as recursive even if it
seems like clever code.


Matt Silberstein

Do something today about the Darfur Genocide

“Darfur: A Genocide We can Stop”

On 2005.12.16 11:51, “ako…” [email protected] wrote:

this one is in haskell:

fibonacci n = round((phi ** (x + 1) - (1 - phi) ** (x + 1)) / (sqrt 5))
where phi = (1 + sqrt 5) / 2
x = (fromInteger n)::Float

fibs :: [Int]
fibs = 0 : 1 : [ a + b | (a, b) ← zip fibs (tail fibs)]

E