Fibonacci數

出自ProgWiki
跳至導覽 跳至搜尋

斐波那契數(Fibonacci Number)

原理

  • F0 = 0
  • F1 = 1
  • Fn = Fn-1 + Fn-2

應用

C++

unsigned int Fibonacci(unsigned int n)
{
    if (n<2)
        return n;
    return Fibonacci(n-1) + Fibonacci(n-2);
}

Java

public unsigned int Fibonacci(unsigned int n) {
    if (n<2) 
        return n;
    return Fibonacci(n-1) + Fibonacci(n-2);
}

JavaScript

function Fibonacci(n) {
    var fib_n = function(curr, next, n) {
        if (n == 0) 
            return curr;
        return fib_n(next, curr+next, n-1);
    }
    return fib_n(0, 1, n);
}

Python

Fibonacci = lambda n: n if n<2 else Fibonacci(n-1) + Fibonacci(n-2)

VB6

Function Fibonacci(ByVal n As ULong) As ULong
    If n < 2 Then Return n Else Return Fibonacci(n - 1) + Fibonacci(n - 2)
End Function