Getting down with Fibonacci

/ 3 Comments

For many Computer Science students, this generic programming problem will be familiar. However, a lot of front-end devs won’t have studied CS (I didn’t). I was asked to interview a CS undergraduate the other day and part of the process was to ask them to solve the following problem:

Write a function that returns the nth term of the Fibonacci sequence

My first question was… “What’s the Fibonacci sequence?”.

After determining what the problem was, I gave it a go myself. My solution is written in JS:

// function accepts the nth term as an argument
function fibonacci(n) {
    
    // validate argument
    if (!n || typeof(n) !== 'number') { return };

    // create an array and start the sequence
    var seq = [0,1];
                                        
    // determine how many iterations are required
    // generate the sequence up to the nth term only
    for (var i = 0; i < (n - 2); i++) {
        // calculate sum of last 2 terms in sequence
        var next = seq[seq.length - 1] + seq[seq.length - 2];
        // add nth term to sequence array
        seq.push(next);
    }
    
    // retrieve last number in sequence
    var x = seq[seq.length - 1];
    return x;
    
}

console.log(fibonacci(20)); // returns 4181​​​​​​​​​​​​​​​​​​​​​​​​​​

Download source files

There are recursive methods, which are more elegant but more expensive. I'm guessing there are also a thousand variations of the approach I took.

3 Comments

  1. Wonderful items from you, man. I have consider your stuff prior to
    and you are just extremely great. I really like what you’ve obtained right here, really like
    what you are stating and the way in which you assert it.
    You’re making it enjoyable and you continue to take care of to keep it
    smart. I can not wait to learn much more from you.

    This is actually a tremendous website.

    my site :: http://Www.Eventbrite.com

  2. You ought to be a part of a contest for one of the
    most useful websites on the web. I am going to recommend this blog!

Leave a Comment