Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@shaungt1
Forked from ihercowitz/goldbach_recursion.js
Created April 27, 2018 04:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shaungt1/d8fe6b1470d89c1f40444e606e30ae43 to your computer and use it in GitHub Desktop.
Save shaungt1/d8fe6b1470d89c1f40444e606e30ae43 to your computer and use it in GitHub Desktop.
Goldbach's conjecture in JavaScript - using Recursion
/* Goldbach's conjecture in JavaScript - using Recursion
*
* author: Igor Hercowitz
*/
function isPrime(n) {
if (n % 2 === 0) return false;
var sqrtn = Math.sqrt(n)+1;
for (var i=3; i < sqrtn; i+=2) {
if (n % i === 0) return false;
}
return true;
}
function primeList(a) {
if (isPrime(a)) return a; else return false;
}
function generateNumbers(initial) {
var num = (initial % 2 === 0)?(initial -1):initial;
var list = []
for (var i = num; i > 3; i-=2)
list.push(i);
list.push(3,1);
return list;
}
function calculate(initial, list, results) {
if (list.length === 0) return results;
var item = list.shift();
var itemPairIndex = list.indexOf(initial - item);
if (itemPairIndex !== -1) {
var itemPair = list.splice(itemPairIndex,1)
results.push(item+"+"+itemPair);
}
return calculate(initial, list, results);
}
function goldbach(initial) {
var pairs = [];
var list = generateNumbers(initial).filter(primeList);
return calculate(initial, list, []);
}
var initial = 10000;
print(initial+" can be represented as: "+(goldbach(initial)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment