Nth Term in the Fibonacci Sequence

Description: Two functions, one using a loop and another a recursive implementation for displaying the Nth term in the sequence.
Tested Platform: .NET 4.8, Visual Studio 2022, Windows 10
Language: C#
// Fibonacci function to find the Nth term in the sequence using a for loop.
private ulong Fibonacci(int nthTerm) {
    if (nthTerm > 1) {
        ulong number1 = 0L;
        ulong number2 = 1L;
        ulong sum = 0L;
        
        // Starting at the second term calculate the nthTerm by adding the last term to the one
        // preceeding it.
        for (int count = 1; count < nthTerm; count++) {
            sum = number1 + number2;
            number1 = number2;
            number2 = sum;
        }

        return sum;
    }
    return 1;
}

// Fibonacci function to find the Nth term in the sequence using recursion (inefficient).
private ulong Fibonacci2(int nthTerm) {
    if (nthTerm > 2) {
        return fibonacci2(nthTerm - 1) + fibonacci2(nthTerm - 2);
    }
    return 1;
}

Posted: March 19, 2023

Return to the snippets listing