JavaScript Implementation of Problem 41

View source code here on GitHub!

Includes

Problem Solution

p0041()

Project Euler Problem 41

Once I found out where the end was, it seemed to be relatively easy

Problem:

We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.

What is the largest n-digit pandigital prime that exists?

Returns:

number --

 1/**
 2 * Project Euler Problem 41
 3 *
 4 * Once I found out where the end was, it seemed to be relatively easy
 5 *
 6 * Problem:
 7 *
 8 * We shall say that an n-digit number is pandigital if it makes use of all the
 9 * digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is
10 * also prime.
11 *
12 * What is the largest n-digit pandigital prime that exists?
13 *
14 * @return {number}
15 */
16exports.p0041 = function() {
17    let answer = -1;
18    for (const p of primes.primes()) {
19        curDigits = p.toString();
20        numDigits = curDigits.length;
21        if (numDigits > 7) {
22            break;
23        }
24        let cont = false;
25        for (const digit of curDigits) {
26            if (parseInt(digit) > numDigits || (curDigits.split(digit).length - 1) !== 1) {
27                cont = true;
28                break;
29            }
30        }
31        if (cont) {
32            continue;
33        } else if (p > answer) {
34            answer = p;
35        }
36    }
37    return answer;
38};
39
40const primes = require('./lib/primes.js');

Tags: pandigital, prime-number, js-iterator