Skip to content

Commit deb80e2

Browse files
author
Daniel Dorado
committed
[CREATE] Project Euler Problem TheAlgorithms#35 done :)
1 parent 3866e8b commit deb80e2

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed

Project-Euler/Problem035.js

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/**
2+
* Problem 35 - Circular primes
3+
*
4+
* @see {@link https://projecteuler.net/problem=35}
5+
*
6+
* The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
7+
* There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
8+
* How many circular primes are there below one million?
9+
*
10+
* @author ddaniel27
11+
*/
12+
13+
/**
14+
* Function to get all prime numbers below a given number
15+
* This function also discards all numbers that contain an even digit
16+
* @see {@link https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes}
17+
*/
18+
function getPrimes (max) {
19+
const sieve = []
20+
const primes = []
21+
22+
for (let i = 2; i <= max; ++i) {
23+
if (!sieve[i]) { // If i has not been marked then it is prime
24+
const hasEven = String(i).split('').some((n) => n % 2 === 0) // Check if i contains an even digit
25+
!hasEven && primes.push(i)
26+
27+
for (let j = i << 1; j <= max; j += i) { // Mark all multiples of i as non-prime
28+
sieve[j] = true
29+
}
30+
}
31+
}
32+
return primes
33+
}
34+
35+
function problem35 (n) {
36+
if (n < 2) {
37+
throw new Error('Invalid input')
38+
}
39+
const list = getPrimes(n)
40+
41+
const result = list.filter((number, _idx, arr) => {
42+
const str = String(number)
43+
const rotations = []
44+
for (let i = 0; i < str.length; i++) { // Get all rotations of the number
45+
rotations.push(str.slice(i) + str.slice(0, i))
46+
}
47+
return rotations.every((rotation) => arr.includes(Number(rotation))) // Check if all rotations are prime
48+
})
49+
50+
return result.length + 1 // Add +1 to the result because 2 is not included in the list
51+
}
52+
53+
export { problem35 }
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
2+
import { problem35 } from '../Problem035.js'
3+
4+
describe('checking circular primes', () => {
5+
it('should be invalid input if number is negative', () => {
6+
expect(() => problem35(-3)).toThrowError('Invalid Input')
7+
})
8+
it('should be invalid input if number is 0', () => {
9+
expect(() => problem35(0)).toThrowError('Invalid Input')
10+
})
11+
// Project Euler Condition Check
12+
test('if the number is equal to 100 result should be 13', () => {
13+
expect(problem35(100)).toBe(13)
14+
})
15+
// Project Euler Challenge Check
16+
test('if the number is equal to one million result should be 55', () => {
17+
expect(problem35(1000000)).toBe(55)
18+
})
19+
})

0 commit comments

Comments
 (0)