Do not input private or sensitive data. View Qlik Privacy & Cookie Policy.
Skip to main content

Announcements
Qlik Open Lakehouse is Now Generally Available! Discover the key highlights and partner resources here.
cancel
Showing results for 
Search instead for 
Did you mean: 
Not applicable

Fibonacci

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

          }

}

1 Solution

Accepted Solutions
Not applicable
Author

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;       

}

View solution in original post

2 Replies
Not applicable
Author

Yes, try not using recursion, something like this:

function Fibonacci(x)

{

     r = 0;

     for i = 1 to x

     {

          r = r + i;

     }

    

     return r;

}

Not applicable
Author

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;       

}