# 每周源代码13 –斐波纳契版

[原文发表时间] 2008-01-23 23:05

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, ...

F#

let rec fib n = if n < 2 then 1 else fib (n-2) + fib(n-1)

let fib_number = int_of_string (System.Environment.GetCommandLineArgs().GetValue(1).ToString());;

let rec fib n = if n < 2 then 1 else fib (n-2) + fib(n-1);;

Printf.printf "\nThe Fibonacci value of %u is: %u\n" fib_number (fib fib_number);;

exit 0;;

Ruby

x1,x2 = 0,1; 0.upto(size){puts x1; x1 += x2; x1,x2 = x2,x1}

class FibonacciGenerator

def printFibo(size)

x1,x2 = 0, 1

0.upto(size){puts x1;x1+=x2; x1,x2= x2,x1} # note the swap for the next iteration

end

f = FibonacciGenerator.new

f.printFibo(10) # print first 10 fibo numbers

end

C#

static int Fibonacci (int x)

{

if (x <= 1)

return 1;

return Fibonacci (x-1) + Fibonacci (x-2);

}

Func<INT , int> fib = null;

fib = n => n > 1 ? fib(n - 1) + fib(n - 2) : n;

Scala

def fib( n: Int): Int = n match {

case 0 => 0

case 1 => 1

case _ => fib( n -1) + fib( n-2)

}

Erlang

fibo(0) -> 0 ;

fibo(1) -> 1 ;

fibo(N) when N > 0 -> fibo(N-1) + fibo(N-2) .