Skip to content

Instantly share code, notes, and snippets.

@StrikingLoo
Created March 23, 2017 04:58
Show Gist options
  • Save StrikingLoo/e5fe5e0b7e603fd6d5d5efd89daf8552 to your computer and use it in GitHub Desktop.
Save StrikingLoo/e5fe5e0b7e603fd6d5d5efd89daf8552 to your computer and use it in GitHub Desktop.
Goldbach's Conjecture
//calling goldbach(n) will give you two prime numbers that add up to it, as long as n is even. Otherwise it will just return [-1,-1]
function findPrimesLowerThan(n){
//find all primes less than or equal to the given n number
primes = [2]
current = 3
while(current<n+1){
isPrime = true
for (i = 0; i<primes.length;i++){
if (current % primes[i]==0){
isPrime = false;
}
}
if(isPrime){
primes.push(current)
}
current++;
}
return primes;
}
//findPrimesLowerThan(5)
function goldbach(n){
//given a natural number n, find the two prime numbers that add up to it.
if(n%2==1){
return [-1,-1]; }
primes= findPrimesLowerThan(n)
for (i = 0 ; i<primes.length ; i++){
for(j = 0 ; j<primes.length;j++){
if (primes[i]+primes[j] == n){
return [primes[i],primes[j]];
}
}
}
}
goldbach(28)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment