返回第N个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; 

🙂

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

只是为了一点乐趣,你可以使用无限的Fibonacci列表和一些IEnumerable扩展来做到这一点

 public IEnumerable Fibonacci(){ var current = 1; var b = 0; while(true){ var next = current + b; yield return next; b = current; current = next; } } public T Nth(this IEnumerable seq, int n){ return seq.Skip.(n-1).First(); } 

获得第n个数字将是

 Fibonacci().Nth(n); 

我认为这应该做的伎俩:

  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; 
  public static int GetNthFibonacci(int n) { var previous = -1; var current = 1; int index = 1; int element = 0; while (index++ <= n) { element = previous + current; previous = current; current = element; } return element; } 
  public IEnumerable 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; } } 

你可以得到第n个数字

  FibonacciBig(100000).Skip(n).First(); 

这是你的作业的解决方案,你应该从3开始,因为你已经有f1和f2的数字(前两个数字)。 请注意,获得第0个斐波纳契数是没有意义的。

 public static UInt64 GetNthFibonacciNumber(uint n) { // Return the nth fibonacci number based on n. if (n == 1 || n == 2) { return 1; } uint a = 1; uint b = 1; uint c; for (uint i = 3; i <= n; i++) { c = b + a; a = b; b = c; } return c; 

}

  public static UInt64 GetNthFibonacciNumber(uint n) { if (n == 0 || n == 1) { return 1; } UInt64 a = 1, b = 1; uint i = 2; while (i <= n) { if (a > b) b += a; else a += b; ++i; } return (a > b) ? a : b; } 
  public static List PrintFibonacci(int number) { List result = new List(); if (number == 0) { result.Add(0); return result; } else if (number == 1) { result.Add(0); return result; } else if (number == 2) { result.AddRange(new List() { 0, 1 }); return result; } else { //if we got thus far,we should have f1,f2 and f3 as fibonacci numbers int f1 = 0, f2 = 1; result.AddRange(new List() { f1, f2 }); for (int i = 2; i < number; i++) { result.Add(result[i - 1] + result[i - 2]); } } return result; }