jar*_*rus 2 c# console-application fibonacci
我正在练习一个C#控制台应用程序,我正在尝试使用该函数来验证该数字是否出现在斐波那契系列中,但是我遇到了错误.
我做的是:
class Program
{
static void Main(string[] args)
{
System.Console.WriteLine(isFibonacci(20));
}
static int isFibonacci(int n)
{
int[] fib = new int[100];
fib[0] = 1;
fib[1] = 1;
for (int i = 2; i <= 100; i++)
{
fib[i] = fib[i - 1] + fib[i - 2];
if (n == fib[i])
{
return 1;
}
}
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
谁能告诉我这里我做错了什么?
Joe*_*orn 19
这是一个使用无限迭代器块的有趣解决方案:
IEnumerable<int> Fibonacci()
{
int n1 = 0;
int n2 = 1;
yield return 1;
while (true)
{
int n = n1 + n2;
n1 = n2;
n2 = n;
yield return n;
}
}
bool isFibonacci(int n)
{
foreach (int f in Fibonacci())
{
if (f > n) return false;
if (f == n) return true;
}
}
Run Code Online (Sandbox Code Playgroud)
我实际上非常喜欢这种斐波纳契实现与传统的递归解决方案,因为它保留了用于完成下一个完成术语的工作.传统的递归解决方案复制了一些工作,因为每个术语需要两次递归调用.
问题出在<=以下声明中:
for (int i = 2; i <= 100; i++)
Run Code Online (Sandbox Code Playgroud)
更重要的是=.没有fib [100](C#零计数)所以当你检查i = 100时你得到一个例外.
适当的陈述应该是
for (int i = 2; i < 100; i++)
Run Code Online (Sandbox Code Playgroud)
甚至更好
for (int i = 2; i < fib.Length; i++)
Run Code Online (Sandbox Code Playgroud)
好吧,对于初学者来说,您的数组只有 10 长,并且您正在用大约 100 个项目(超出范围的异常)填充它-但是有更好的方法可以做到这一点...
例如,使用这篇文章:
long val = ...
bool isFib = Fibonacci().TakeWhile(x => x <= val).Last() == val;
Run Code Online (Sandbox Code Playgroud)
这是一个击败你所有人的解决方案!
因为,当智能数学家为您做封闭式解决方案时,为什么要进行迭代?:)
static bool IsFibonacci(int number)
{
//Uses a closed form solution for the fibonacci number calculation.
//http://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression
double fi = (1 + Math.Sqrt(5)) / 2.0; //Golden ratio
int n = (int) Math.Floor(Math.Log(number * Math.Sqrt(5) + 0.5, fi)); //Find's the index (n) of the given number in the fibonacci sequence
int actualFibonacciNumber = (int)Math.Floor(Math.Pow(fi, n) / Math.Sqrt(5) + 0.5); //Finds the actual number corresponding to given index (n)
return actualFibonacciNumber == number;
}
Run Code Online (Sandbox Code Playgroud)