2.3 KiB
2.3 KiB
id | challengeType | title |
---|---|---|
5900f3931000cf542c50fea5 | 5 | Problem 38: Pandigital multiples |
Description
Instructions
Tests
tests:
- text: <code>pandigitalMultiples()</code> should return 932718654.
testString: assert.strictEqual(pandigitalMultiples(), 932718654, '<code>pandigitalMultiples()</code> should return 932718654.');
Challenge Seed
function pandigitalMultiples() {
// Good luck!
return true;
}
pandigitalMultiples();
Solution
function pandigitalMultiples() {
function get9DigitConcatenatedProduct(num) {
// returns false if concatenated product is not 9 digits
let concatenatedProduct = num.toString();
for (let i = 2; concatenatedProduct.length < 9; i++) {
concatenatedProduct += num * i;
}
return concatenatedProduct.length === 9 ? concatenatedProduct : false;
}
function is1to9Pandigital(num) {
const numStr = num.toString();
// check if length is not 9
if (numStr.length !== 9) {
return false;
}
// check if pandigital
for (let i = 9; i > 0; i--) {
if (numStr.indexOf(i.toString()) === -1) {
return false;
}
}
return true;
}
let largestNum = 0;
for (let i = 9999; i >= 9000; i--) {
const concatenatedProduct = get9DigitConcatenatedProduct(i);
if (is1to9Pandigital(concatenatedProduct) && concatenatedProduct > largestNum) {
largestNum = parseInt(concatenatedProduct);
break;
}
}
return largestNum;
}