Skip to content

Instantly share code, notes, and snippets.

@bartcis
Last active July 31, 2019 14:20
Show Gist options
  • Select an option

  • Save bartcis/d38112e268416eb80189f3d40b223c55 to your computer and use it in GitHub Desktop.

Select an option

Save bartcis/d38112e268416eb80189f3d40b223c55 to your computer and use it in GitHub Desktop.
Find sum of all prime numbers within given range
function sumPrimesBasic(number) {
// 1. Create final sum and call function for finding primes
const findPrimes = (maximum) => {
// 2. Inside function that finds prime declare initial variables
let filter = [],
primes = [];
// 3. Loop through number smaller than the argument
for (let i = 2; i <= maximum; i++) {
// 4. This array contains multiplications. If it's there a number can't be prime
if (!filter[i]) {
// 5. If condition is met add it to primes
primes.push(i);
// 6. Find all multiplications of the number within given range
for (let j = i; j <= maximum; j += i) {
// 7. If a value has multiplications within given range flag them
filter[j] = true;
}
}
}
return primes;
};
// 8. Sum up all values from the array
return findPrimes(number).reduce((a, b) => a + b);
}
console.time('Start Algo 1');
console.log(sumPrimesBasic(10));
console.timeEnd('Start Algo 1'); // Start Algo 1: 0.97802734375ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment