我见过类似的问题(但在C中) - Calculating Fibonacci Numbers Recursively in C关于我的问题。
在我的控制台应用程序的C#中,我有点坚持如何继续打印斐波纳契数字,直到它达到大约40,000,我怎样才能实现这个目标?
E.G,我希望应用程序执行此操作:
0
1
1
2
3
5
8
and so on.
感谢。 我不想这么说,但我有一个脑电波,并解决了它!
这是我做的:
static void Main(string[] args)
{
int num1 = 0;
int num2 = 1;
int sum = 1;
while (num1 <= 15000)
{
sum = num1 + num2;
num1 = num2;
num2 = sum;
Console.WriteLine(num2);
}
Console.ReadLine();
}
答案 0 :(得分:6)
只是为了好玩,我想我会用LINQ扩展方法和一个生成器(无限序列)以一种有趣的方式来做这件事:
// A utility class that holds math utility functions.
public static class MathUtility
{
// This method returns the fibonacci sequence which is an
// infinite sequence of numbers where each result is the
// sum of the previous two results.
public static IEnumerable<int> GetFibonacciSequence()
{
int first = 0;
int second = 1;
// first and second result are always 1.
yield return first;
yield return second;
// this enumerable sequence is bounded by the caller.
while(true)
{
int current = first + second;
yield return current;
// wind up for next number if we're requesting one
first = second;
second = current;
}
}
}
这会产生一个无限的(理论上)序列(如果让它超过int的范围,它最终会溢出)。
然后你可以打电话:
foreach(var num in MathUtility.GetFibonacciSequence().TakeWhile(num => num <= 40000))
{
Console.WriteLine(num);
}
通过这种方式,您可以将演示文稿(输出)与数据生成分开。
答案 1 :(得分:3)
有一个循环的东西怎么样?像:
static void main()
{
int num1 = 0;
int num2 = 1;
int sum = 1;
Console.WriteLine(num1);
while (sum < 40000)
{
sum = num1 + num2;
num1 = num2;
num2 = sum;
Console.WriteLine(num2);
}
}
答案 2 :(得分:2)
static int Fibonacci(int n)
{
if(n <= 1) return n;
else return Fibonacci(n - 1) + Fibonacci(n - 2);
}
static void PrintAllFibonacci()
{
int n = 0;
while(true)
Console.WriteLine(Fibonacci(n++));
}
编辑:
使用堆栈的不同方法
static ulong Fibonacci(int n, IList<ulong> stack)
{
ulong fibonacci;
if (n <= 1)
{
fibonacci = (ulong)n;
}
else
{
ulong n1, n2;
if (n < stack.Count)
n1 = stack[n - 1];
else
n1 = Fibonacci(n - 1, stack);
if (n - 1 < stack.Count)
n2 = stack[n - 2];
else
n2 = Fibonacci(n - 2, stack);
fibonacci = n1 + n2;
}
if (n >= stack.Count)
stack.Add(fibonacci);
return fibonacci;
}
static void PrintAllFibonacci()
{
var stack = new List<ulong>();
var n = 0;
while(n < 50)
Console.WriteLine(n + ") " + Fibonacci(n++, stack));
}
答案 3 :(得分:1)
你不能递归地做 - 记住,每个方法调用都使用你的堆栈。谷歌,关于,堆栈溢出:)
你需要找到算法的迭代版本,它在互联网上无处不在。而且,当然,虽然fib数字很快就会快速运行,但是永远无法输出它们。
答案 4 :(得分:1)
public static long ClosedFormFibonacci(int i)
{
const double phi = 1.61803398874989; // or use your own or calculate it
const double sqrt5 = 2.23606798; // same as above
return (long)Math.Round(Math.Pow(phi, i) / sqrt5);
}
看起来它在第92个斐波那契数字上溢出了很长时间
答案 5 :(得分:0)
C#不容易支持尾递归,所以做一个简单的递归算法会导致堆栈溢出,数量足够大。对于这个问题,最简单的方法是使用循环而不是递归。如果你真的坚持递归,here是一篇博客文章,研究伪造递归和转换C#生成的IL代码以使用尾递归。
答案 6 :(得分:0)
您的计划有两个主要错误: