Pages

Monday, August 29, 2016

JS recursive function exercise

If I hear the word fibonacci again, I'm going to vomit.   So, I'll skip the fib question from the website that I'm stealing all these problems from:  http://www.w3resource.com/javascript-exercises/javascript-recursion-functions-exercises.php

I'm sorry, I am just so sick of Fibs and freaking fizz-buzz.  Are there no other examples out there?

Well, maybe there just is a reason, so let's do the Fib problem after all.  Just deal with it:


Write a recursive program to get the first n Fib numbers.

For example, fib(7) would output [1,1,2,3,5,8,13];

However, this is worth doing and seeing the answer in the comments, because this is probably the smartest solution to this problem that I've ever seen.




1 comment:

  1. var fibonacci_series = function (n)
    {
    if (n===1)
    {
    return [0, 1];
    }
    else
    {
    var s = fibonacci_series(n - 1);
    s.push(s[s.length - 1] + s[s.length - 2]);
    return s;
    }
    };

    ReplyDelete