How may I change my let oddNumbersArr=newArr.filter(e=>e%2==1) to get only prime numbers?
function sumPrimes(num) {
let newArr=[];
for(let i=0;i<=num;i++){
newArr.push(i)
}
let oddNumbersArr=newArr.filter(e=>e%2==1)
(elements=>elements>1)
let sumOfAll=greaterThanOneArr.reduce((a,b)=>a+b,0)
console.log(sumOfAll)
}
sumPrimes(10);
Yes., I can explain it. I can get the prime number ef a number with it. My problem is the next one: I cannot do it with every number from 2 until num. For example: If I set 10, I cannot get nothing because it is not prime, but if I set 2, I can get 2 because it can be divided by itself, therefore it is a prime number and It cannot be diveded by another number.
Your function makes a list of numbers that divide evenly into num. That will not be a list of prime numbers. Prime numbers have no divisors except for 1 and themselves.
Ah, I see. Why make a list? Why not stop as soon as any number divides your number?
This approach is slow and expensive, but you can wrap that logic in an outer loop and replace num in the i loop bound with the outer loop variable. It’ll work but will be very slow for large num.
I still think the seive algorithm is easier to code.
Note: I was serious when I asked you to explain your logic. Converting code to a verbal explanation is an important debugging technique. I really was hoping that you would write out the logic in words.
Yup, that’s an example of a nested loop. If you use your inner loop to test if a number is prime and use the outer loop to cover all numbers from 1 to num, it will work (albeit slowly).
You are checking num each inner loop. You will get (partial) results for the primality of num unless you use the outer loop to change which number you are checking.