Sum All Primes(help)

Sum All Primes(help)
0

#1

Tell us what’s happening:
I wrote a function to find out whether a number is prime or not and that seems to work fine.
But, it doesn’t work while i try to add the primes.
I don’t understand why this doesn’t work?

if(isPrime(j)){
newArr.push(j);
}

Your code so far


function isPrime(num1){
	var remainder = [];
	var squareroot = Math.floor(Math.sqrt(num1))
	for(let i=2;i<squareroot;i++){
		remainder.push(num1%i);
	}
	if(remainder.includes(0)){
		return false;
	}
	return true;
	}
function sumPrimes(num) {
  var newArr =[]
  for(let j=1;j<num;j++){
    if(isPrime(j)){
      newArr.push(j);
    }
  }

  return newArr.reduce(((a,b) => a+b),0);
}

sumPrimes(10);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-primes


#2

Your isPrime function is not working. I’d suggest re-examining it then go from there. You can walk thru the function in the debugger console using a debugger statement as

function isPrime(num1){
  debugger;
	var remainder = [];
	var squareroot = Math.floor(Math.sqrt(num1))
	for(let i=2;i<squareroot;i++){
		remainder.push(num1%i);
	}
	if(remainder.includes(0)){
		return false;
	}
	return true;
	}
function sumPrimes(num) {
  debugger;
  var newArr =[]
  for(let j=1;j<num;j++){
    if(isPrime(j)){
      newArr.push(j);
    }
  }

  return newArr.reduce(((a,b) => a+b),0);
}

and opening the console before running the tests. Or, put console.log statements in your code and see what happens in the console.


#3
	for(let i=2;i<squareroot;i++){
		remainder.push(num1%i);
	}

You have a logic error here. When you sumPrimes(10) the first 8 numbers don’t enter this loop at all because squareroot is 2. For 9, which is a perfect square, it only checks 2 and never does num1%3 because your loop stops before the floored square root.


#4

Hi there,

I am also working on the same algoritm and…it works in the console, in Node or CodePen but not with FreeCodeCamp:

function sumPrimes(num) {
  let myArr = [];
  function isPrime(num) {
    for(let i = 2; i < num; i++)
      if(num % i === 0) return false;
    return num !== 1;
  }
  for(let j = 0; j<= num; j++){
    if(isPrime(j)){
      myArr.push(j);
    }
  }
  let allSum = myArr.reduce((a,b)=> a + b);
  return allSum;
}

sumPrimes(10);

I’m getting this

commons-b48a099b457b77b5ddc8.js:sourcemap:28 TypeError: unknown: Cannot read property ‘0’ of undefined

I don’t understand what is the problem…


#5

Also, your code needs to be efficient or else it won’t pass the final test case.


#6
 for(let i = 2; i < num; i++)
      if(num % i === 0) return false;

You need to either put curly braces ({}) around the contents of your for loop.


#7

It works in jsfiddle as well. It seems that FCC needs the braces around the for loop; without them, syntactically, it’s fine, but you get the error as you noted.

for (let i = 2; i < num; i++) { 
     if (num % i === 0) return false; 
}
	return (num !== 1);

#8

Yes, it seems so ! Thanks for the help, I couldn’t understand the problem.


#9

Thanks @ArielLeslie for reply,
When i test isPrime() function in console, it seems to work fine.
It identifies the prime number correctly.
Could you please elaborate the mistake i am making?


#10

as mentioned in the message i sent you:


#11

Your code works. But, I have a question:
sumPrimes(6); //15

By mathematics, only 1,2,3 and 5 are prime numbers before 6 and they all add up to 11.
Dont you think there is a problem with this function you’ve written?


#12

Thanks for the reply.
But, when i run the isPrime() function in chrome console it identifies the prime numbers correctly.
Why is that?


#13

hi Aditya, can you tell me exactly what steps you are doing to test? (give as much detail as possible starting with which page you are on when you are using chrome, which keys you are typing, what code you pasted , which key you clicked). As I don’t have experience running javascript in the console I won’t be able to help till I see exactly what you are doing.


#14

Ok, so chrome console works same on all the pages.
I opened the console by pressing (F12) key on keyboard.
Then i wrote this code :

function isPrime(num){
	var remainder = [];
	var squareroot = Math.floor(Math.sqrt(num))
	for(let i=2;i<squareroot;i++){
		remainder.push(num%i);
	}
	if(remainder.includes(0)){
		return false;
	}
	return true;
	}

The logic that goes behind this code is :
1) When i wish to find out whether a number is prime or not, what i have to do is check its divisibility by all the numbers which are less than squareroot of that number.
2) If a number has squareroot in decimal values(which most of the numbers have), then i just convert that into integer by Math.floor() function.
3) If the number is not divisble by any of the numbers less than its squareroot, it is a prime number.
4) So, in the code, i declared an empty array "remainder" first and then, i calculated the squareroot of the num and converted it into integer. And then, i started the loop with initial value of 2 because if it initializes with 1, num will always be divisible by 1.
5) Now, num is divided and by all the number in loop, and the remainder is pushed to remainder array.
6) If the num is divisible by any of the values in loop, the remainder array will have 0 as one of its elements.
7) Thus, if remainder array contains 0 function isPrime() returns false else it returns true i.e the number is prime.

I have checked for several test cases and function works all the time.
But when it is inside the sumPrimes() it does not work.


#15

Sorry to interject AGAIN. You didnt answer the question I asked about your function. I noticed it still doesn’t filter out non-prime numbers.
Your isPrime() function needs to be debugged, because, until it filters out non-prime numbers, it will not be able to pass the FCC tests.


#16

I followed your steps and the isPrime function doesn’t work in my chrome console (it thinks 9 is prime). Maybe you are doing something else that I’m not doing?


#17

In your for loop, you need i <= squareroot as the bound is sometimes sharp (i.e., squares of a prime will only have this one factor).


#18

Ohh!!!, thanks for that 9 test case.
I tried many test cases but somehow didn’t notice that code doesn’t work for a few odd perfect squares.
That happened because i didn’t got the squareroot variable right because of Math.floor(Math.sqrt(num)) functionality.
I made one change and now the code works.
This is isPrime() function:

function isPrime(num){
	var remainder = [];
	var squareroot = Math.floor(Math.sqrt(num))	+1;
	for(let i=2;i<=squareroot;i++){
		remainder.push(num%i);
	}
	if(remainder.includes(0)){
		return false;
	}
	return true;
	}

I also passed the challenge after one more change:

function sumPrimes(num) {
  var newArr =[]
	function isPrime(num1){
	var remainder = [];
	var squareroot = Math.floor(Math.sqrt(num1)) +1;
	for(let i=2;i<squareroot;i++){
		remainder.push(num1%i);
	}
	if(remainder.includes(0)){
		return false;
	}
	return true;
	}
  for(let j=2;j<num;j++){
    if(isPrime(j)){
	console.log(newArr)
      newArr.push(j)
    }
  }

  return newArr.reduce(((a,b) => a+b),0);
}

I changed the initial value of j to 2 cause 1 is not a prime number and it passed.


#19

sounds good. You should definitely always add logs whenever you are questioning the results.


#20

Thank you so much @ArielLeslie, @parramorej, @omeizahanif and @mathic for the help.
I appreciate all of you guys’ help.