ADDITION OF PRIME NUMBER FROM 1 TO 100 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

10th Feb 2022, 3:03 PM
Ibrahim Yusuf
Ibrahim Yusuf - avatar
7 Answers
+ 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.
10th Feb 2022, 6:47 PM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 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)
10th Feb 2022, 5:08 PM
Denise Roßberg
Denise Roßberg - avatar
+ 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)
10th Feb 2022, 6:05 PM
Denise Roßberg
Denise Roßberg - avatar
+ 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.
10th Feb 2022, 7:30 PM
Ibrahim Yusuf
Ibrahim Yusuf - avatar
+ 3
You're welcome :)
10th Feb 2022, 7:35 PM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 2
I WAS SO HAPPY THAT I WILL BE ABLE TO HELP SOMEONE BUT UNFORTUNATELY I CAN ONLY HELP YOU IN PYTHON CODES 😔.
21st Apr 2022, 12:04 PM
AARAV PANDEY
AARAV PANDEY - avatar
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
10th Feb 2022, 5:19 PM
Ibrahim Yusuf
Ibrahim Yusuf - avatar