Skip to content

Commit

Permalink
Tune performance of p60
Browse files Browse the repository at this point in the history
  • Loading branch information
LivInTheLookingGlass committed Aug 22, 2024
1 parent 081d5f4 commit 25f9669
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 17 deletions.
2 changes: 0 additions & 2 deletions docs/src/javascript/p0060.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ View source code :source:`javascript/src/p0060.js`

.. js:autofunction:: p0060

.. js:autofunction:: isConcatPrime

.. literalinclude:: ../../../javascript/src/p0060.js
:language: javascript
:linenos:
Expand Down
29 changes: 14 additions & 15 deletions javascript/src/p0060.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,24 @@ exports.p0060 = function() {
iterator.next(); // 5 is excluded because if a number ends with 5, it's divisible by 5
const compat = new Map();
for (const x of iterator) {
const strX = String(x);
for (const y of cachedPrimes) {
if (isConcatPrime(x, y)) {
if (primes.isPrime(Number(`${strX}${y}`)) && primes.isPrime(Number(`${y}${strX}`))) {
for (const [a, b, c] of iters.combinations(compat.get(y) || new Set(), 3)) {
// remember these checks are commutative
if (compat.get(b).has(a) && compat.get(c).has(a) && compat.get(c).has(b)) {
if (isConcatPrime(a, x) && isConcatPrime(b, x) && isConcatPrime(c, x)) {
const strA = String(a);
const strB = String(b);
const strC = String(c);
const concatenations = [
Number(`${strA}${strX}`),
Number(`${strX}${strA}`),
Number(`${strB}${strX}`),
Number(`${strX}${strB}`),
Number(`${strC}${strX}`),
Number(`${strX}${strC}`)
];
if (concatenations.every(primes.isPrime)) {
return x + y + a + b + c;
}
}
Expand All @@ -44,18 +56,5 @@ exports.p0060 = function() {
return -1;
};

/**
* Tests if a pair of numbers generates a prime if concatenated in both orders.
*
* @param {number} x
* @param {number} y
* @return {number}
*/
const isConcatPrime = function(x, y) {
const sx = x.toString();
const sy = y.toString();
return primes.isPrime(parseInt(sx + sy)) && primes.isPrime(parseInt(sy + sx));
};

const iters = require('./lib/iters.js');
const primes = require('./lib/primes.js');

0 comments on commit 25f9669

Please # to comment.