Skip to content

Instantly share code, notes, and snippets.

@ihercowitz
Created February 22, 2012 00:48
Show Gist options
  • Save ihercowitz/1880259 to your computer and use it in GitHub Desktop.
Save ihercowitz/1880259 to your computer and use it in GitHub Desktop.
Goldbach's conjecture
/* Goldbach's conjecture in JavaScript
*
* 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 goldbach(initial, list) {
var pairs = [];
while (list.length >0) {
var item = list.shift();
var itemPairIndex = list.indexOf(initial - item);
if (itemPairIndex !== -1) {
var itemPair = list.splice(itemPairIndex,1)
pairs.push(item+"+"+itemPair);
}
}
return pairs;
}
var initial = 40000;
print(initial+" can be represented as: "+(goldbach(initial, generateNumbers(initial).filter(primeList))));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment