From c353c4c659c3dcb19524ba893f170805c931a44a Mon Sep 17 00:00:00 2001 From: Aditya Date: Sat, 10 Nov 2018 12:49:16 +0530 Subject: [PATCH] fix(curriculum): Problem 35 - update solution --- .../problem-35-circular-primes.english.md | 77 ++++++++++++------- 1 file changed, 50 insertions(+), 27 deletions(-) diff --git a/curriculum/challenges/english/08-coding-interview-prep/project-euler/problem-35-circular-primes.english.md b/curriculum/challenges/english/08-coding-interview-prep/project-euler/problem-35-circular-primes.english.md index 463120caf9..84bab43cbe 100644 --- a/curriculum/challenges/english/08-coding-interview-prep/project-euler/problem-35-circular-primes.english.md +++ b/curriculum/challenges/english/08-coding-interview-prep/project-euler/problem-35-circular-primes.english.md @@ -9,6 +9,9 @@ title: 'Problem 35: Circular primes' 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 n, whereas 100 <= n <= 1000000? + +
Note:
+Circular primes individual rotation can exceeed `n`. ## Instructions @@ -63,37 +66,57 @@ circularPrimes(1000000); ```js -const circularPrimes = (n) => { - const primeCheck = (num) => { - if (num === 1) { - return false; - } - for (let i = 2; i <= Math.floor(Math.sqrt(num)); i++) { - if (num % i === 0) { - return false; - } - } - return true; - }; - let count = 1; - for (let i = 1; i < n; i += 2) { - if (primeCheck(i)) { - let flag = true; - let circularNum = i.toString(); - for (let j = 1; j < i.toString().length; j++) { - circularNum = circularNum.substring(1) + circularNum.substring(0, 1); - if (primeCheck(Number(circularNum)) === false) { - flag = false; - break; - } - } - if (flag) { - count++; +function rotate(n) { + if (n.length == 1) return n; + return n.slice(1) + n[0]; +} + +function circularPrimes(n) { + // Nearest n < 10^k + const bound = 10 ** Math.ceil(Math.log10(n)); + const primes = [0, 0, 2]; + let count = 0; + + // Making primes array + for (let i = 4; i <= bound; i += 2) { + primes.push(i - 1); + primes.push(0); + } + + // Getting upperbound + const upperBound = Math.ceil(Math.sqrt(bound)); + + // Setting other non-prime numbers to 0 + for (let i = 3; i < upperBound; i += 2) { + if (primes[i]) { + for (let j = i * i; j < bound; j += i) { + primes[j] = 0; } } } + + // Iterating through the array + for (let i = 2; i < n; i++) { + if (primes[i]) { + let curr = String(primes[i]); + let tmp = 1; // tmp variable to hold the no of rotations + for (let x = rotate(curr); x != curr; x = rotate(x)) { + if (x > n && primes[x]) { + continue; + } + else if (!primes[x]) { + // If the rotated value is 0 then its not a ciruclar prime, break the loop + tmp = 0; + break; + } + tmp++; + primes[x] = 0; + } + count += tmp; + } + } return count; -}; +} ```