Returning Nth Fibonacci number the sequence?

2019-02-03 22:54发布

I have a question on my homework for class and I need to know how to return nth number of Fibonacci sequence using iteration (no recursion allowed).

I need some tips on how to do this so I can better understand what I am doing wrong. I output to the console in my program.cs, hence it being absent in the code below.

    // 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;

8条回答
狗以群分
2楼-- · 2019-02-03 23:26

I think this should do the trick:

    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;
查看更多
倾城 Initia
3楼-- · 2019-02-03 23:26
    public IEnumerable<BigInteger> FibonacciBig(int maxn)
    {
        BigInteger Fn=1;
        BigInteger Fn_1=1;
        BigInteger Fn_2=1;

        yield return Fn;
        yield return Fn;

        for (int i = 3; i < maxn; i++)
        {
            Fn = Fn_1 + Fn_2;

            yield return Fn;

            Fn_2 = Fn_1;
            Fn_1 = Fn;
        }


    }

you can get the n-th Number by

   FibonacciBig(100000).Skip(n).First();
查看更多
登录 后发表回答