Skip to content

Commit 0529e19

Browse files
authored
solution: Project Euler 35 (TheAlgorithms#1201)
* [CREATE] Problem 28 solution for Project Euler * [UPDATE] Added an explanation for the formula used in the algorithm * [CREATE] Added Problem 35 for Project-Euler * [UPDATE] Little typo in the error string * [UPDATE] Some algorithm changes * [UPDATE] Fix test string * [UPDATE] Change prime numbers generator to import a standard sieve algorithm. * [UPDATE] Change sieve algorithm implementation and now the solution works well. Also added some optimizations
1 parent 72ee63c commit 0529e19

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

Project-Euler/Problem035.js

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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+
import { sieveOfEratosthenes } from '../Maths/SieveOfEratosthenesIntArray'
13+
14+
function problem35 (n) {
15+
if (n < 2) {
16+
throw new Error('Invalid input')
17+
}
18+
const list = sieveOfEratosthenes(n).filter(prime => !prime.toString().match(/[024568]/)) // Get a list of primes without 0, 2, 4, 5, 6, 8
19+
20+
const result = list.filter((number, _idx, arr) => {
21+
const str = String(number)
22+
for (let i = 0; i < str.length; i++) { // Get all rotations of the number
23+
const rotation = str.slice(i) + str.slice(0, i)
24+
if (!arr.includes(Number(rotation))) { // Check if the rotation is prime
25+
return false
26+
}
27+
}
28+
return true // If all rotations are prime, then the number is circular prime
29+
})
30+
31+
return result.length + 1 // Add 2 to the result because 2 is a circular prime
32+
}
33+
34+
export { problem35 }

Project-Euler/test/Problem035.test.js

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import { problem35 } from '../Problem035.js'
2+
3+
describe('checking circular primes', () => {
4+
it('should be invalid input if number is negative', () => {
5+
expect(() => problem35(-3)).toThrowError('Invalid input')
6+
})
7+
it('should be invalid input if number is 0', () => {
8+
expect(() => problem35(0)).toThrowError('Invalid input')
9+
})
10+
// Project Euler Condition Check
11+
test('if the number is equal to 100 result should be 13', () => {
12+
expect(problem35(100)).toBe(13)
13+
})
14+
// Project Euler Challenge Check
15+
test('if the number is equal to one million result should be 55', () => {
16+
expect(problem35(1000000)).toBe(55)
17+
})
18+
})

0 commit comments

Comments
 (0)