Proposed Solution for : Intermediate Algorithm Scripting: Sum All Primes

function sumPrimes(num) {
  if (num > 1){
    let sum = 0;
     // Loop through each element from 2 to num
    for (let i = 2; i <= num; i++) {
      let count = 0;
      // Loop through numbers from 1 to i, and count the divisors
      for (let j = 1; j <= i; j++) {
        if (i % j === 0) {
          count ++;
      // If the divisors count is more than 2, that means it is not a prime number
     //If the count is equal to 2, then it is a prime number
      if (count === 2) {
        sum = sum + i;//add the prime number to the sum
    return sum;}

Hey, thanks for the enthusiasm and desire to submit new official solutions.

This is a particularly inefficient solution, which is similar to some of the other solutions, so I don’t know that this solution helps future campers a lot.

You can use techniques like discussed in this post (below) to measure performance.

1 Like

I am just a noob, so i might do mistakes…
Can you please specify exactly what you think is inefficient in the code?
I’d like to know more please!

You don’t need to count, as soon as you find a divisor, you know the number isn’t prime.

You’re checking way more values than you need to here.

Right now, you are dividing n*n + (n-1)*(n-1) + (n-2)*(n-2) + ... + 2*2 times. This can be cut down quite a lot.

If you use some clever math that people thought up centuries ago (that’s what I did for mine), you can get even faster.

But, isn’t the computer is doing those calculations very fast? why do i have to worry about how much i am dividing?

Little computations add up. Supercomputers are the fastest computers we have, and we still worry about not doing extra calculations on them.

My two rules for efficient code are:

  1. Don’t do calculation you don’t need to

  2. Don’t store data you don’t need to

You are doing a lot of extra calculation you don’t need.

Your solution is O(num^2), which is a fancy way of saying the time to solution is proportional to the square of num.

The solution I linked is O(num log(log(num)), which is much, much faster.