mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-05-13 06:04:13 -04:00
fix(curriculum): faster euler 32 ref solution (#61274)
This commit is contained in:
committed by
GitHub
parent
af26a7c18a
commit
5e1990ee1c
@@ -70,45 +70,43 @@ pandigitalProducts(4);
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function pandigitalProducts(n) {
|
||||
function is1toNPandigital(n, digitStr) {
|
||||
// check if length is n
|
||||
if (digitStr.length !== n) {
|
||||
return false;
|
||||
}
|
||||
// check if pandigital
|
||||
for (let i = digitStr.length; i > 0; i--) {
|
||||
if (digitStr.indexOf(i.toString()) === -1) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function concatenateNums(...numbers) {
|
||||
let digitStr = '';
|
||||
for (let i = 0; i < numbers.length; i++) {
|
||||
digitStr += numbers[i].toString();
|
||||
}
|
||||
return digitStr;
|
||||
}
|
||||
// Check for pandigital number
|
||||
function isPandigital(digitStr) {
|
||||
return digitStr
|
||||
.split('')
|
||||
.sort()
|
||||
.every((c, i) => c == i + 1);
|
||||
}
|
||||
|
||||
const pandigitalNums = [];
|
||||
const limit = 10 ** Math.floor(n / 2) - 1;
|
||||
// Concatenate 3 numbers
|
||||
function concatenate3Nums(a, b, c) {
|
||||
return a.toString() + b.toString() + c.toString();
|
||||
}
|
||||
|
||||
// Find sum of all pandigital products
|
||||
function pandigitalProducts(n) {
|
||||
const products = [];
|
||||
let sum = 0;
|
||||
for (let mult1 = 2; mult1 < limit; mult1++) {
|
||||
for (let mult2 = 2; mult2 < limit; mult2++) {
|
||||
const product = mult1 * mult2;
|
||||
const concatenated = concatenateNums(mult1, mult2, product);
|
||||
const max = Number(Array(n)
|
||||
.fill(0)
|
||||
.map((_, i) => (n - i).toString())
|
||||
.join(''));
|
||||
const outerLimit = Math.sqrt(max);
|
||||
|
||||
for (let factor1 = 2; factor1 < outerLimit; factor1++) {
|
||||
const innerLimit = max / factor1;
|
||||
|
||||
for (let factor2 = factor1; factor2 < innerLimit; factor2++) {
|
||||
const product = factor1 * factor2;
|
||||
const concatenated = concatenate3Nums(factor1, factor2, product);
|
||||
|
||||
if (concatenated.length > n) {
|
||||
break;
|
||||
} else if (concatenated.length < n) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
is1toNPandigital(n, concatenated) &&
|
||||
!pandigitalNums.includes(product)
|
||||
} else if (concatenated.length == n &&
|
||||
isPandigital(concatenated) &&
|
||||
!products.includes(product)
|
||||
) {
|
||||
pandigitalNums.push(product);
|
||||
products.push(product);
|
||||
sum += product;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user