Getting down with Fibonacci →
/ 1 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
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.
Very elegant solution