JavaScript Algorithm: Sum of All Primes
stuxnat
Posted on January 16, 2022
This problem asks to return sum of all prime numbers that are less than or equal to a given number.
A prime number is a whole number greater than 1 with exactly two divisors: 1 and itself.
Here is how to solve that algorithm:
Step 1. Set up the algorithm, accounting for the number 2 (the lowest prime):
function sumprime(num){
if (num < 2){
return 0;
}
return num;
}
sumprime(10);
Step 2. If num is greater than 2, we want to keep track of all the prime numbers up to and including the given parameter. We will need to use a for loop to check for composite numbers (the opposite of prime).
function sumprime(num){
if (num < 2){
return 0;
}
const primes = [];
for (let i = 2; i <= num; i++){
let composite = false;
for (const p of primes){
if (i % p === 0){
composite = true;
break;
}
}
if (!composite){
primes.push(i)
}
}
console.log(primes)
return num;
}
sumprime(10);
Step 3. Sum up the numbers!
function sumprime(num) {
if (num < 2) {
return 0;
}
const primes = [];
for (let i = 2; i <= num; i++) {
let composite = false;
for (const p of primes) {
if (i % p === 0) {
composite = true;
break;
}
}
if (!composite) {
primes.push(i)
}
}
let sum = 0;
for (const p of primes) {
sum += p;
}
return sum;
}
sumprime(10);
💖 💪 🙅 🚩
stuxnat
Posted on January 16, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.