Returning Nth Fibonacci number the sequence?(返回第 N 个斐波那契数列?)
问题描述
我有一个关于课堂作业的问题,我需要知道如何使用迭代返回第 n 个斐波那契数列(不允许递归).
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).
我需要一些关于如何执行此操作的提示,以便更好地了解我做错了什么.我在我的 program.cs 中输出到控制台,因此在下面的代码中不存在.
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;
推荐答案
:)
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);
}
                        这篇关于返回第 N 个斐波那契数列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:返回第 N 个斐波那契数列?
				
        
 
            
        - 在 LINQ to SQL 中使用 contains() 2022-01-01
 - Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
 - 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
 - 在 C# 中异步处理项目队列 2022-01-01
 - 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
 - Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
 - 使用 rss + c# 2022-01-01
 - C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
 - CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
 - 带问号的 nvarchar 列结果 2022-01-01
 
						
						
						
						
						