Unlock a world of possibilities! Login now and discover the exclusive benefits awaiting you.
I'm using Javascript to create the Fibonacci function and the performance is bad and the program crashes with Fibonacci(45) and upper on an 8 core i7 CPU second generation. I've noticed Javascript don't use my CPU at 100% only at 12%.
Isn't there a good way to create a Fibonacci function with good performance?
function Fibonacci(x)
{
if (x == 0)
{
return 0;
}
else if (x == 1)
{
return 1;
}
else
{
return Fibonacci(x - 1) + Fibonacci(x - 2);
}
}
My own answer to my own question:
function FibIter(n)
{
u = 0;
v = 1;
if(n==0) return 0;
if(n==1) return 1;
for(i = 2; i <= n; i++)
{
t = u + v;
u = v;
v = t;
}
return v;
}
Yes, try not using recursion, something like this:
function Fibonacci(x)
{
r = 0;
for i = 1 to x
{
r = r + i;
}
return r;
}
My own answer to my own question:
function FibIter(n)
{
u = 0;
v = 1;
if(n==0) return 0;
if(n==1) return 1;
for(i = 2; i <= n; i++)
{
t = u + v;
u = v;
v = t;
}
return v;
}