JavaScript Algorithm: Sum of All Primes

stuxnat

stuxnat

Posted on January 16, 2022

JavaScript Algorithm: Sum of All Primes

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); 
Enter fullscreen mode Exit fullscreen mode

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); 
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
stuxnat
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.

Related

What was your win this week?
weeklyretro What was your win this week?

November 29, 2024

Where GitOps Meets ClickOps
devops Where GitOps Meets ClickOps

November 29, 2024

How to Use KitOps with MLflow
beginners How to Use KitOps with MLflow

November 29, 2024