Home > OS >  I write a function to find the prime number , but it's not working because I'm not able to
I write a function to find the prime number , but it's not working because I'm not able to

Time:05-29

function isPrime(n) {

    if (n == 1 ) {
        return (`${n} is niether a prime number nor composite number`)
    }
    else if( n < 1){
        return (`${n} is not a prime number`)
    }
    else{
        for (let i = 2;  i < n; i  ) {
            if( n % 2 == 0){
                return result = `${n} is not a prime number`
                break;
            }
            else{
                return result = `${n} is a prime number`
            }
        }
    }
}

console.log(isPrime(15))

I write a function to find the prime number , but it's not working because I'm not able to break the loop

CodePudding user response:

Although answer by Dave addresses the question I would suggest this stack overflow answer as an better alternative.

https://stackoverflow.com/a/38643868/10738743

CodePudding user response:

There are two glitches preventing your function working as intended.

  1. the loop which tests for primeness is repeating n%2 on each iteration, which will evaluate the same, regardless of the value of i in the loop. Instead, you should be testing to see whether n%i is true.

  2. With that fixed, the final return (which only happens if all non-prime conditions have been rejected with earlier returns) should be outside of any block as it becomes the default return value.

your code functions fine with the minor changes suggested above incorporated:

function isPrime(n) {
if (n == 1 ) {
    return (`${n} is niether a prime number nor composite number`);
}
else if( n < 1){
    return (`${n} is not a prime number`)
}
else {
    for (let i = 2;  i < n; i  ) {
        if( n % i == 0){
            return result = `${n} is not a prime number`
            // break; // (return breaks anyway)
        } // end if       
    }// end for i;
    
    } // end else
    
    return result = `${n} is a prime number`; // default after no earlier rejection

}

console.log(isPrime(15)); 

  • Related