c# - 返回第 N 个斐波那契数列?

标签 c# iteration fibonacci

我的类作业有一个问题,我需要知道如何使用迭代返回第 n 个斐波那契数列(不允许递归)。

我需要一些关于如何执行此操作的提示,以便我可以更好地理解我做错了什么。我在我的 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;

最佳答案

:)

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);
}

关于c# - 返回第 N 个斐波那契数列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13018278/

相关文章:

c# - 在 IValidatableObject 上设置 ValidationContext 的 Items 集合?

c# - 如何在 vb.net 中获取 OCX 的位置和文件名

c++ - 迭代合并排序,与冒泡排序速度相同

python - 枚举二进制变量值的所有可能组合

ruby - 斐波那契线

php - 循环遍历描述螺旋的公式以生成 XY 坐标

c# - 编写 unittest 以创建一个文件,然后删除该文件

c# - 想在 asp.net 中使用 c++ 库和 dll

javascript - 如何只删除对象的值?

Python:斐波那契数列