計算第 n 個斐波納契數

與大多數語言一樣,Visual Basic.NET 允許遞迴,這是一個函式在某些條件下呼叫自身的過程。

這是 Visual Basic .NET 中用於計算 Fibonacci 數的基本函式。

''' <summary>
''' Gets the n'th Fibonacci number
''' </summary>
''' <param name="n">The 1-indexed ordinal number of the Fibonacci sequence that you wish to receive. Precondition: Must be greater than or equal to 1.</param>
''' <returns>The nth Fibonacci number. Throws an exception if a precondition is violated.</returns>
Public Shared Function Fibonacci(ByVal n as Integer) as Integer
    If n<1
        Throw New ArgumentOutOfRangeException("n must be greater than or equal to one.")
    End If
    If (n=1) or (n=2)
        ''Base case. The first two Fibonacci numbers (n=1 and n=2) are both 1, by definition.
        Return 1
    End If
    ''Recursive case.
    ''Get the two previous Fibonacci numbers via recursion, add them together, and return the result.
    Return Fibonacci(n-1) + Fibonacci(n-2)
End Function

此函式首先檢查是否已使用引數 n 等於 12 呼叫該函式。根據定義,Fibonacci 序列中的前兩個值是 1 和 1,因此不需要進一步計算來確定這一點。如果 n 大於 2,我們就不能輕易查詢相關值,但我們知道任何這樣的 Fibonacci 數等於前兩個數的總和,所以我們通過遞迴請求它們 (呼叫我們自己的 Fibonacci 函式)。由於連續的遞迴呼叫通過遞減 -1 和 -2 來呼叫越來越少的數字,我們知道最終它們將達到小於 2 的數字。一旦達到這些條件(稱為基本情況 ),堆疊就會展開,我們得到我們的最終結果。