- 1

I this the right way to check whether a number is prime , not prime or a negative number in JavaScript

Plss answer https://code.sololearn.com/WXp4w3bdL9U2/?ref=app

13th May 2021, 3:39 PM
roshan roy
4 Respuestas
+ 2
It is, but there are a few improvements you can implement to improve your code. Firstly consider putting this inside a function so that you run your primality check on more than just your hard-coded number. Secondly, and perhaps the bigger point... Loops in programming are expensive. They take a long time to run, and if you're not careful, they can quickly grind your program to a halt. That being said, there are two areas I can see to speed up this program. First, if the number is negative, there's no need to check if it's prime; a negative number, by definition, cannot be prime. So move that if num< 0 bit to the top. We can actually extend this pre-check a bit: any number less than 2 is not prime. So if our number is 0 or 1, it's not prime. Secondly, let's consider the range of numbers we'd need to check a number (for example, 21) against to check if it's prime. In short, we want to start at 2 and divide by each number (2, 3, 4, etc.) until we either run out of numbers we wanna divide by, or we (cont'd)
14th May 2021, 8:34 PM
HealyUnit
HealyUnit - avatar
+ 2
hit a number where our num%this test num == 0. But here's the thing: we only need to test up to the square root of the number. Any number above that square root, and we've already tested it indirectly. Consider our example number, 21. When we test 3, we're also testing 7 (because 21/3=7). We're saying "when I divide 21 by 3, is the answer a whole number?", and then answering "yes, it's 7", which implicitly means the reverse is true. These changes are part of a larger concept called "time complexity". In short, if possible, you want to design your code so that it takes as little time as possible to run thru a particular problem
14th May 2021, 8:40 PM
HealyUnit
HealyUnit - avatar
+ 1
Yeah it seems to be correct
13th May 2021, 3:44 PM
YUGRAJ
0
YUGRAJ thanks brother.
14th May 2021, 5:02 AM
roshan roy