Fibonacci Numbers

Author: Theodore Odeluga

The source files for this project can be downloaded from here

This is a Node command line project and Node.js can be downloaded from here

Instructions for running a command line program with Node.js can be found here

This project started life as a C++ program and its simplicity still surprises me.

It seems a fluke that the amount of implementation required was so little. I was expecting the expression of Fibonacci in code to get quite complicated.

Converting the earlier source to JavaScript was equally easy so without further ado lets grab all the results.

As we know, Fibonacci is a series where every third number is a sum of the previous two and surely enough this code only requires three variables.

As with other examples, the trusty i variable continues to serve as an iterator.

The first variable, surprise surprise, represents the first number in the sequence. Second is the second and sum stores the two of them added together.

First then increments itself by one, and so does second.

first += 1;
second += 1;

A while loop opens up next and limits itself by the value of num, a single parameter in the samples only function.

while (i < num) {
first += second;
second += first;
sum = first + second;
i++;
console.log(first);
console.log(second);
}

The next bit is interesting. I found this worked (admittedly more by luck than design) with just two lines.

As you can see, inside the loop on the first line the ‘first’ variable is incremented by ‘second’ and then on the second line ‘second’ is incremented by ‘first’.

Sum then aggregates the two while i adds an additional step each time (continuing until the end as defined by num).

As the while loop repeats, each of the two components of sum continue to increment the other while the results repeatedly print themselves to the screen. Finally, the numbers are output according to the style of Fibonacci.

Here’s the entire the program for convenience.

let i = 0;
let first = 0;
let second = 0;
let sum;

function fibonacci(num){

first += 1;
second += 1;

while (i < num) {
first += second;
second += first;
sum = first + second;
i++;
console.log(first);
console.log(second);
}
}

fibonacci(5);

Conclusion

Sometimes complexity can be boiled down to a few simple steps. I’m glad its been the case for me here and I hope it was easy enough and clear for you to follow along as well. Thanks for reading.