Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

Below is my code to check whether a number is prime or not:

function isPrime(num) {

  if (num === 2) {

    return true;

  } else if (num > 1) {

    for (var i = 2; i < num; i++) {

      if (num % i !== 0) {

        return true;

      } else if (num === i * i) {

        return false

      } else {

        return false;

      }

    }

  } else {

    return false;

  }

}

console.log(isPrime(121));

When I run the above code, it doesn’t work for the square of odd prime numbers. For example, 9 returns true instead of false. 

Can anyone tell me how to do a prime number test in JavaScript?

1 Answer

0 votes
by (19.7k points)

See the below code implementation: 

function isPrime(num) {

  for(var i = 2; i < num; i++)

    if(num % i === 0) return false;

  return num > 1;

}

Below is the code implementation with ES6 syntax:

const isPrime = num => {

  for(let i = 2; i < num; i++)

    if(num % i === 0) return false;

  return num > 1;

}

If you want to decrease the complexity of the algorithm from O(n) to O(sqrt(n)), run the loop until the square root of a number:

const isPrime = num => {

    for(let i = 2, s = Math.sqrt(num); i <= s; i++)

        if(num % i === 0) return false; 

    return num > 1;

}

Interested in Java? Check out this Java Certification by Intellipaat.

Related questions

0 votes
1 answer
+7 votes
1 answer
0 votes
1 answer
asked Dec 17, 2020 in Python by ashely (50.2k points)
0 votes
1 answer
asked Apr 19, 2021 in Java by sheela_singh (9.5k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...