JavaScript Implementation of Problem 37

View source code here on GitHub!

Includes

Problem Solution

p0037()

Project Euler Problem 37

I was surprised how fast my brute-force solution went, but it worked

Problem:

The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.

Find the sum of the only eleven primes that are both truncatable from left to right and right to left.

NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.

Returns:

number --

 1/**
 2 * Project Euler Problem 37
 3 *
 4 * I was surprised how fast my brute-force solution went, but it worked
 5 *
 6 * Problem:
 7 *
 8 * The number 3797 has an interesting property. Being prime itself, it is possible
 9 * to continuously remove digits from left to right, and remain prime at each
10 * stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797,
11 * 379, 37, and 3.
12 *
13 * Find the sum of the only eleven primes that are both truncatable from left to
14 * right and right to left.
15 *
16 * NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.
17 *
18 * @return {number}
19 */
20exports.p0037 = function() {
21    let answer = 0;
22    let count = 0;
23    for (const p of primes.primes()) {
24        if (count == 11) {
25            break;
26        } else if (p < 10) {
27            continue;
28        } else {
29            let right = p;
30            let left = p;
31            while (primes.isPrime(right)) {
32                right = 0 | (right / 10);
33            }
34            if (right != 0) {
35                continue;
36            }
37            while (primes.isPrime(left)) {
38                let x = 10;
39                while (x < left) {
40                    x *= 10;
41                }
42                left %= 0 | (x / 10);
43            }
44            if (left != 0) {
45                continue;
46            }
47            answer += p;
48            count++;
49        }
50    }
51    return answer;
52};
53
54const primes = require('./lib/primes.js');

Tags: prime-number, digit-manipulation, js-iterator