+ 1
ADDITION OF PRIME NUMBER FROM 1 TO 100
Please can someone help me with why I’m getting empty array even tho my isPrime function is correct. I’m trying to print array of prime number from 1 to 100 then sum them up. Any way I could correct this https://code.sololearn.com/WbFocj7pyCz4/?ref=app
7 Antworten
+ 3
You have a problem with hoisting of the (undeclared) loop variable 'i'.
To prevent hoisting, you can block scope the loop variables using 'let':
for(let i = 1, ...) {...}
That fixes one issue. The other has been mentioned by Denise Roßberg. The array 'arr' is global. That messes up your isPrime function. Put it locally inside that function instead so that it is reset to [] each time the function runs.
+ 3
Ibrahim Yusuf
Did you tested your isPrime function?
Normally you would just do this (pseudocode)
for(i = 2; i <= sqrt(num); i++){
if(num % i) == 0 return false;
}
return true;
sqrt = square root
(not sure if it exists in javacript)
+ 3
Ibrahim Yusuf
Sorry I'm not familiar with js.
But it looks like arr is a global variable. And I guess this could be the problem.
Ignoring sumUp try this to see why isPrime is not working in your loop:
//arr is empty
console.log(isPrime(7)) //true
console.log(arr) //arr is filled
console.log(isPrime(13)) //false
console.log(arr)
+ 3
Denise Roßberg Ani Jona 🕊
Thank you so much guys. The code was affected by both global variable and undeclared loop variable “i”. That was really helpful.
+ 3
You're welcome :)
+ 2
I WAS SO HAPPY THAT I WILL BE ABLE TO HELP SOMEONE BUT UNFORTUNATELY I CAN ONLY HELP YOU IN PYTHON CODES 😔.
0
Denise Roßberg
Yes I did. The isPrime function is running perfectly. But when I try to pass arguement to isPrime function using loop, I keep getting false