返回第N个Fibonacci数序列?

use*_*351 7 c# iteration fibonacci

我对课堂作业有疑问,我需要知道如何使用迭代返回第n个Fibonacci序列(不允许递归).

我需要一些关于如何做到这一点的提示,以便我能更好地理解我做错了什么.我在program.cs中输出到控制台,因此它在下面的代码中不存在.

    // Q1)
    //
    // Return the Nth Fibonacci number in the sequence
    //
    // Input: uint n (which number to get)
    // Output: The nth fibonacci number
    //

    public static UInt64 GetNthFibonacciNumber(uint n)
    {

    // Return the nth fibonacci number based on n.


    if (n == 0 || n == 1)
        {
            return 1;
        }

        // The basic Fibonacci sequence is 
        // 1, 1, 2, 3, 5, 8, 13, 21, 34...
        // f(0) = 1
        // f(1) = 1
        // f(n) = f(n-1) + f(n-2)
        ///////////////
        //my code is below this comment

        uint a = 0;
        uint b = 1;

        for (uint i = 0; i < n; i++)
        {
            n = b + a;
            a = b;
            b = n;
        }
        return n;
Run Code Online (Sandbox Code Playgroud)

L.B*_*L.B 10

:)

static ulong Fib(int n) 
{
    double sqrt5 = Math.Sqrt(5);
    double p1 = (1 + sqrt5) / 2;
    double p2 = -1 * (p1 - 1);


    double n1 = Math.Pow(p1, n + 1);
    double n2 = Math.Pow(p2, n + 1);
    return (ulong)((n1 - n2) / sqrt5);
}
Run Code Online (Sandbox Code Playgroud)

  • 为何如此有用:http://en.wikipedia.org/wiki/Square_root_of_5#Relation_to_the_golden_ratio_and_Fibonacci_numbers (2认同)

Shm*_*dty 1

我认为这应该可以解决问题:

    uint a = 0;
    uint b = 1;
    uint c = 1;

    for (uint i = 0; i < n; i++)
    {
        c = b + a;
        a = b;
        b = c;
    }
    return c;
Run Code Online (Sandbox Code Playgroud)