I just finished solving Project Euler's 50th problem, but it's awfully slow. I'd like to hear your thoughts on my code's efficiency and practices.
Problem Statement
The prime 41, can be written as the sum of six consecutive primes:
\$41 = 2 + 3 + 5 + 7 + 11 + 13\$
This is the longest sum of consecutive primes that adds to a prime below one-hundred.
The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.
Which prime, below one-million, can be written as the sum of the most consecutive primes?
Code
let primeNumbers = [];
function isPrime(number) { // checks whether number is prime or not
for(let i = 2; i <= number / 2; i++) { // stops checking at 1/2 of number
if (number % i === 0) return false;
}
return true;
}
function storePrimes(count) {
for(let i = 2; i < count; i++) { // starts at 2
if (isPrime(i)) {
primeNumbers.push(i);
}
}
}
function findLargestSum() {
let termsCount = 0;
let sumOfTerms = 0;
primeNumbers.forEach(currentSum => { // keeps track of possible sum
primeNumbers.forEach((startNumber, startIndex) => { // keeps track of start index
let consecutiveCount = 0;
let consecutiveSum = 0;
primeNumbers.forEach((prime, primeIndex) => { // iterates through primes
if (primeIndex >= startIndex) { // applies start index
consecutiveCount++;
consecutiveSum += prime;
if (consecutiveCount > termsCount && consecutiveSum === currentSum) {
termsCount = consecutiveCount;
sumOfTerms = consecutiveSum;
}
}
})
})
})
return {largestSum: sumOfTerms, termsCount: termsCount};
}
function findPrimes(count) {
storePrimes(count)
let results = findLargestSum();
console.log("Largest sum'o'primes of prime consecutives under " + count + " is: " + results.largestSum + " with " + results.termsCount + " terms.");
}
findPrimes(1000000);
Sieve of Eratosthenes
since this question seems to be a duplicate. You can read about that on google or even search in the search bar here. There are lots of already answered questions. Also you can go for sqrt(n) + 1 instead of n/2 for the function isprime. \$\endgroup\$