JavaScript Implementation of Problem 35

View source code here on GitHub!

Includes

Problem Solution

p0035()

Project Euler Problem 35

This ended up being a filtering problem. The problem with my solution is that I am not satisfied with my filter at all. I feel like there is a more efficient way to go about it.

Problem:

The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.

There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.

How many circular primes are there below one million?

Returns:

number --

 1/**
 2 * Project Euler Problem 35
 3 *
 4 * This ended up being a filtering problem. The problem with my solution is that I
 5 * am not satisfied with my filter at all. I feel like there is a more efficient
 6 * way to go about it.
 7 *
 8 * Problem:
 9 *
10 * The number, 197, is called a circular prime because all rotations of the
11 * digits: 197, 971, and 719, are themselves prime.
12 *
13 * There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71,
14 * 73, 79, and 97.
15 *
16 * How many circular primes are there below one million?
17 *
18 * @return {number}
19 */
20exports.p0035 = function() {
21    let answer = 0;
22    for (let x = 0; x < 1000000; x++) {
23        let broken = false;
24        for (const rot of rotations(x)) {
25            if (!primes.isPrime(rot)) {
26                broken = true;
27                break;
28            }
29        }
30        if (!broken) {
31            answer++;
32        }
33    }
34    return answer;
35};
36
37/**
38 * Iterate over the rotations of a number's decimal representation
39 * @param {number} x
40 * @yield {number}
41 */
42function* rotations(x) {
43    yield x;
44    const xs = x.toString();
45    for (let i = 1; i < xs.length; i++) {
46        yield Number(xs.substring(i) + xs.substring(0, i));
47    }
48}
49
50const primes = require('./lib/primes.js');

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