Created
August 26, 2016 05:44
-
-
Save hugdx/53337fc969878f9f26d4a8403b4031ca to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function primeSum(n, k) { | |
if( k === 1 ){ | |
return isPrime(n); | |
} | |
var aListPrime = getListPrime(n); | |
log('aListPrime', aListPrime); | |
//log('aTable', aTable); | |
var aListNumber = aListPrime; | |
var aTables = []; | |
var aTable = {}; | |
while( k >= 2 ){ | |
aTable = buidTable(aListNumber, n); | |
aListNumber = Object.keys(aTable); | |
k = k - 2; | |
// for track | |
aTables.push(aTable); | |
} | |
log("k", k); | |
log('aTables', aTables); | |
if( k===0 ){ | |
if( aTable[n] !== undefined ){ | |
console.log("==> found: n =", aTable[n]); | |
return true; | |
} | |
console.log("Not found for ",n); | |
return false; | |
} | |
// for k =3, 5 | |
if( k === 1 ){ | |
var iLen = aTable.lengh; | |
var iTmpl = 0; | |
for(var iSum in aTable){ | |
iTmpl = n - iSum; | |
if( aListPrime.indexOf(iTmpl) !== -1 ){ | |
console.log("==> found: n =", iTmpl, " + ", iSum); | |
return true; | |
} | |
} | |
console.log("Not found for ",n); | |
return false; | |
} | |
} | |
function log(name, aVal){ | |
console.log(name," = ", JSON.stringify(aVal, null, 4)); | |
} | |
function isPrime(n){ | |
if( n <= 1 ) | |
return false; | |
if( n===2 ) | |
return true; | |
var sqrtn = Math.sqrt(n) + 1; | |
for(var i = 2; i< sqrtn; i++){ | |
if( n% i ===0) | |
return false; | |
} | |
return true; | |
} | |
function getListPrime(n){ | |
var aListPrime = []; | |
for(var i = 2; i<=n;i++){ | |
if( isPrime(i) ) | |
aListPrime.push(i); | |
} | |
return aListPrime; | |
} | |
function buidTable( aListPrime, n ){ | |
var aTable = {}; | |
var iLen = aListPrime.length; | |
for(var i =0; i< iLen; i++){ | |
for(var j =0; j< iLen; j++){ | |
var iSum = parseInt(aListPrime[i]) + parseInt(aListPrime[j]); | |
if( iSum <= n ){ | |
aTable[iSum] = aTable[iSum] || []; | |
aTable[iSum].push([aListPrime[i],aListPrime[j]]); | |
} | |
} | |
} | |
// sort | |
iLen = aTable.length; | |
for(var i =0; i < iLen; i++){ | |
for(var j=i+1;j<iLen-1; j++){ | |
if( aTable[i] > aTable[j] ){ | |
var aTmpl = aTable[i]; | |
aTable[i] = aTable[j]; | |
aTable[i] = aTmpl; | |
} | |
} | |
} | |
return aTable; | |
} | |
/* | |
console.clear(); | |
var iStart = (new Date()).getTime(); | |
primeSum(9, 3); | |
console.info( (new Date()).getTime() - iStart ); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment