I am trying to get the first 100 fibonacci numbers to output to a .txt file. I got it to run, but it's taking a while. Will fibonacci or fibonacci2 be faster? The code below uses the first one.
#!/usr/bin/env node
var fs = require('fs');
// Fibonacci
// http://en.wikipedia.org/wiki/Fibonacci_number
var fibonacci = function(n) {
if(n < 1) { return 0;}
else if(n == 1 || n == 2) { return 1;}
else if(n > 2) { return fibonacci(n - 1) + fibonacci(n - 2);}
};
// Fibonacci: closed form expression
// http://en.wikipedia.org/wiki/Golden_ratio#Relationship_to_Fibonacci_sequence
var fibonacci2 = function(n) {
var phi = (1 + Math.sqrt(5))/2;
return Math.round((Math.pow(phi, n) - Math.pow(1-phi, n))/Math.sqrt(5));
};
// Find first K Fibonacci numbers via basic for loop
var firstkfib = function(k) {
var i = 1;
var arr = [];
for(i = 1; i < k+1; i++) {
var fibi = fibonacci(i);
arr.push(fibi);
// Print to console so I can monitor progress
console.log(i + " : " + fibi);
}
return arr;
};
var fmt = function(arr) {
return arr.join(",");
};
var k = 100;
// write to file
var outfile = "fibonacci.txt";
var out = fmt(firstkfib(k));
fs.writeFileSync(outfile, out);
console.log("\nScript: " + __filename + "\nWrote: " + out + "\nTo: " + outfile);