Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

My code is saying that number 1 is prime. How to fix that?

So,

I’m starting to learn how to code and now I have only one problem.
My code is functioning very well, until he says that the numbers 1 and 0 are prime.

I already tried to add them to exception, change the calculation and still printing that is prime.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here’s the code:

function testPrimeNumber(num)
{
    Number(num)
    for (var i = 2; i < num; i++)
    {
        if (num % i == 0)                
        {
            return ("The number "+num+" isn't prime.");                
        }                                
        else {}                
    }      
    return ("The number "+num+" is prime.");   
} 

console.log("result for 1:", testPrimeNumber(1));

What am I doing wrong here?

>Solution :

You should test for 0 and 1 at the start of the function. At the moment your code is skipping the for loop (because 1 < 2 and 0 < 2) and going straight to saying the number is prime.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading