Sum All Primes Implementation

Tell us what’s happening:

Well, i’m not very good at mathematics. And this algorithm is giving me a quite headache. Even when i was in school and that’s long time ago, i don’t remember in curriculum that i had prime numbers. Truth be told, i was in sort of “trade school” … Thus being said, easiest algorithm i could find(and understand) is Sieves . It works on smaller sequences, but on larger ones … not very precise, or at least not my implementation of it. I know how to do it by hand, i learn that first, but checking such a large sequence by hand is ludicrous. Can someone, at least point me in right direction regarding possible mistakes in my code or implementation of it? Keep in mind English ain’t my native tongue nor am i proficient in mathematics. PS: It been quite a few days first by doing this by hand and quite more doing it in JS.

Your code so far

function sumPrimes(num) {

	var br=0;
	var arr=[];
	for(var i=0;i<num;i++){
	
		arr.push(isPrime(i));
	
	}
	
	var arr1=[];
	for(var i=0;i<arr.length;i++){

		if(arr[i]==true){
			arr1.push(i);
		}

	}

	for(var i=0;i<arr1.length;i++){

		br+=arr1[i];
	}
    console.log(br);
  
  //console.log();
    return br;
}

function isPrime(brx){

    if(brx < 2){ 
      return false;
    }
  
    if(brx == 2) {
      return true;
    }
  
    if(brx % 2 == 0) {
      return false;
    }
  
    for(var i=3; (i*i)<=brx; i+=2){
      
        if(brx % i == 0 ) {
          return false;
        }
      
    }
    return true;

}

sumPrimes(10);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36.

Link to the challenge:
https://www.freecodecamp.org/challenges/sum-all-primes

Pretty damned good for a guy who thinks he’s not good at math!

In the Sieve you start with a range of numbers up to num inclusively.
0 to10 including 10 or 0 to 977 including 977. Confirm that all of the range is being tested.

Good luck. You’re so close.

PS you cut the first line of your code off in your post. I figured it out though.

Ooh, sorry about missing line. 10+ hours per day for almost a week will do that to ya. Corrected that.

for(var i=0;i<=num;i++){ Needed to add = “equal sign” between “<” and num variable at first loop right after array “arr” declaration.
From place where am i coming from, i’m i’m worst at mathematics, at least in my surroundings.

It works for me! Good job.

A good introduction to the “off by one error”.
Unfortunately the real world is not zero-indexed.