// Fibonacci // http://en.wikipedia.org/wiki/Fibonacci_number var isPrime = function(n, arr) { for (var i = 0; i < arr.length; i++) { if (arr[i] > Math.sqrt(n)) { break; } if ((n % arr[i]) == 0) { return false; } } return true; }; // Fibonacci: closed form expression // http://en.wikipedia.org/wiki/Golden_ratio#Relationship_to_Fibonacci_sequence var calculatePrime = function(arr) { if(arr.length == 0) { return [2]; } var i = arr[arr.length - 1] + 1; while (!isPrime(i, arr)) { i = i + 1; } arr.push(i) return arr; }; // Find first K Fibonacci numbers via basic for loop var firstPrimeNumber = function(k) { var i = 1; var arr = []; while (arr.length < k) { arr = calculatePrime(arr); } return arr; }; // Print to console var fmt = function(arr) { return arr.join(","); //return arr; }; var k = 100; //console.log("firstkfib(" + k + ")"); //console.log(fmt(firstPrimeNumber(k))); var fs = require('fs'); var outfile = "prime.txt"; var out = fmt(firstPrimeNumber(k)); fs.writeFileSync(outfile, out); //console.log("Script: " + __filename + "\nWrote: " + out + "To: " + outfile);
↧
Calculate Primes
↧