Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number prime test in JavaScript

Tags:

javascript

I'm trying to complete the Codewars challenge that asks you to check if a number is a prime number. For whatever reason, my solution doesn't seem to work for the square of odd prime numbers (e.g. 9 returns true instead of false).

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));

P.s. I included that second else/if statement because I was trying to solve the problem.

like image 433
John Ozenua Avatar asked Oct 23 '16 06:10

John Ozenua


People also ask

How do you test if a number is prime?

To prove whether a number is a prime number, first try dividing it by 2, and see if you get a whole number. If you do, it can't be a prime number. If you don't get a whole number, next try dividing it by prime numbers: 3, 5, 7, 11 (9 is divisible by 3) and so on, always dividing by a prime number (see table below).

Is a number prime Codewars?

Per Wikipedia, a prime number ( or a prime ) is a natural number greater than 1 that has no positive divisors other than 1 and itself.


1 Answers

Time complexity: O(sqrt(n))

Space complexity: O(1)

const isPrime = num => {     for(let i = 2, s = Math.sqrt(num); i <= s; i++)         if(num % i === 0) return false;      return num > 1; } 
like image 173
Ihor Sakailiuk Avatar answered Sep 20 '22 12:09

Ihor Sakailiuk