mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 16:26:47 +08:00
added more comments and standardized code
This commit is contained in:
@ -1,30 +1,31 @@
|
|||||||
// https://projecteuler.net/problem=7
|
// https://projecteuler.net/problem=7
|
||||||
|
// My approach does not use the Sieve of Eratosthenes but that is another common way to approach this problem. Sieve of Atkin is another possibility as well.
|
||||||
|
|
||||||
const num = 10001;
|
const num = 10001
|
||||||
|
const primes = [2, 3, 5, 7, 11, 13] // given list of primes you start with
|
||||||
let primes = [2,3,5,7,11,13]; // given list of primes you start with
|
|
||||||
|
|
||||||
const calculatePrime = (num) => {
|
const calculatePrime = (num) => {
|
||||||
let count = primes.length; // count number of primes calculated
|
// Calculate each next prime by checking each number to see what it's divisible by
|
||||||
let current = primes[count-1] + 1; // current number being assessed if prime
|
let count = primes.length // count number of primes calculated
|
||||||
|
let current = primes[count - 1] + 1 // current number being assessed if prime
|
||||||
while (count < num) { // repeat while we haven't reached goal number of primes
|
while (count < num) { // repeat while we haven't reached goal number of primes
|
||||||
// go through each prime and see if divisible by the previous primes
|
// go through each prime and see if divisible by the previous primes
|
||||||
let prime = false;
|
let prime = false
|
||||||
primes.some((n, i) => {
|
primes.some((n, i) => {
|
||||||
if (current % n === 0) {
|
if (current % n === 0) {
|
||||||
return true;
|
return true
|
||||||
}
|
}
|
||||||
if (i === count-1) {
|
if (i === count - 1) {
|
||||||
prime = true;
|
prime = true
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
if (prime) {
|
if (prime) { // if prime, add to prime list and increment count
|
||||||
primes.push(current);
|
primes.push(current)
|
||||||
count += 1;
|
count += 1
|
||||||
}
|
}
|
||||||
current += 1;
|
current += 1
|
||||||
}
|
}
|
||||||
return primes[num-1];
|
return primes[num - 1]
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(calculatePrime(num));
|
console.log(calculatePrime(num))
|
||||||
|
Reference in New Issue
Block a user