Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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