﻿ [Ruby] Fibonacci 數列....(頁 1) - 網路時代 - 程式語言 - Math Pro 數學補給站

## Math Pro 數學補給站's Archiver

### [Ruby] Fibonacci 數列....

"Peter Ertl" <p...@gmx.org>

that why I love ruby (and functional languages in general)

[code]def fibonacci(n)
a, b = 1, 1
n.times do
a, b = b, a + b
end
a
end [/code]

elegance beats ignorance (ruby vs. java)

---------------------------------------------------------------------------------

[b][i]Christian Neukirchen <chneukirc...@gmail.com>

That's not functional...

How about really doing it functional?

[code]def fib(n)
(1..n-2).inject([1, 1]) { |(a, b), n| [b, a+b] }.last
end [/code]

:)

---------------------------------------------------------------------------------

[b][i]Edward Faulkner <e...@alum.mit.edu>

If we're talking about elegance, I prefer this one.  It reads just
like the definition of the sequence:

[code]def fib(n)
n > 1 ? fib(n-1) + fib(n-2) : n
end [/code]

You can even make it run efficiently by memoizing it.  :-)

-Ed

---------------------------------------------------------------------------------

[b][i]"Andrew Backer" <awbac...@gmail.com>

[code]def calc_iterative(n)
a = [0,1,0]
for i in 2..n
a[k] = a[k-1] + a[k-2]
end
return a[n%3]
end [/code]

I like this one, since it uses array wrapping.  So many ways to write
it that are all *slightly*  different... But this was to show someone,
so :)