88

Check Number prime in JavaScript

let inputValue= 7;
let isprime=inputValue==1? false:true;  //bcoz 1 is not prime

for(let i=2;i<inputValue;i++){
  inputValue%i==0? isprime*=false :isprime*=true;
};

alert(`${inputValue} is ${isprime? 'prime':'not prime'} number`);
patrick.elmquist
  • 2,113
  • 2
  • 21
  • 35
John Ozenua
  • 1,035
  • 1
  • 8
  • 5

47 Answers47

257

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;
}
Ihor Sakailiuk
  • 5,642
  • 3
  • 21
  • 35
  • 6
    What the check for equality to `4` there is for? One may also only check the odd numbers. – zerkms Oct 23 '16 at 08:33
  • 2
    so make it `i <= s` and remove that ugly hardcoded condition? – zerkms Oct 23 '16 at 08:46
  • 1
    Thanks, I've removed this useless check. – Ihor Sakailiuk Oct 23 '16 at 08:53
  • 4
    @Saka7 This was a really helpful answer, especially because of the `sqrt` optimization, which I hadn't considered. @zerkms Suggested only checking the odd numbers (greater than two of course), which is something I expected to see as well in an optimized solution. You can greatly optimize your solution this way. I've made [this JSPerf test](https://jsperf.com/math-isprime/1) to demonstrate. Thanks, to both of you for the guidance BTW. – gfullam Jan 17 '18 at 16:53
  • 2
    `isPrime(0)` returns `true`, which is not the case. For the function to be mathematically correct, you need to add another condition to the return statement: `return num !== 1 && num !== 0;` – pavloko May 22 '18 at 16:28
  • 3
    Instead of `return num !== 1 && num !== 0;` you can just use condition `return num >= 2;` since prime numbers must be natural numbers greater than 1. – Angel Cloudwalker Feb 13 '19 at 19:59
  • 1
    Why does the square root optimization work? Isn't it possible for a number to be divisible by an integer greater than its square root? For example, the square root of 10 is about 3.16, but 10 is divisible by 5 which is greater than this. **Update:** This answers my question: https://stackoverflow.com/a/5811176/414220 – evanrmurphy Feb 25 '19 at 19:45
  • Junior question - how does it get to `3` and return T? (This does work I checked). The loop condition stops it from even performing any logic. Isn't `Math.sqrt(3) //=> 1.7320508 < 2`. Just curious – Mote Zart Mar 23 '19 at 22:49
  • @MoteZart `isPrime(3)` returns `true` because of `num > 1` (`3 > 1`) condition in the return statement. – Ihor Sakailiuk Mar 24 '19 at 12:46
  • 1
    But aren't all the prime numbers found already (up to some insanely big number)? Why do we keep calculating them? – jayarjo Apr 06 '19 at 17:00
  • This is very inefficient, don't use loops for something like this... Check my answer for the most CPU easy way to find a prime number... [here](https://stackoverflow.com/a/59010810/9926342) – 255.tar.xz Nov 23 '19 at 18:26
  • your case is failing in case of number `57` which is not prime but showing it is prime number. – Pardeep Jain Dec 18 '19 at 18:18
  • @Pardeep Jain Are you sure? `isPrime(57)` returns `false` as expected – Ihor Sakailiuk Dec 19 '19 at 07:47
  • You can actually half it's time complexity by making i increase by 2 each time and make i start at 3. Because whenever i is equal to an even number it is unnecessary because any value who's multiple is an even number will always be a multiple of 2 – destroyer22719 Mar 17 '22 at 16:46
  • I can't believe that this is the accepted answer! There is an elegant implication: if `n` is a prime number greater than 5, then `n=6k+-1`; this implication is implemented by @H S Progr's answer. – Kedar Mhaswade Jun 07 '22 at 12:32
31

A small suggestion here, why do you want to run the loop for whole n numbers?

If a number is prime it will have 2 factors (1 and number itself). If it's not a prime they will have 1, number itself and more, you need not run the loop till the number, may be you can consider running it till the square root of the number.

You can either do it by euler's prime logic. Check following snippet:

function isPrime(num) {
  var sqrtnum=Math.floor(Math.sqrt(num));
    var prime = num != 1;
    for(var i=2; i<sqrtnum+1; i++) { // sqrtnum+1
        if(num % i == 0) {
            prime = false;
            break;
        }
    }
    return prime;
}

Now the complexity is O(sqrt(n))

For more information Why do we check up to the square root of a prime number to determine if it is prime?

Hope it helps

Valera
  • 2,665
  • 2
  • 16
  • 33
Geeky
  • 7,420
  • 2
  • 24
  • 50
17
function isPrime(num) { // returns boolean
  if (num <= 1) return false; // negatives
  if (num % 2 == 0 && num > 2) return false; // even numbers
  const s = Math.sqrt(num); // store the square to loop faster
  for(let i = 3; i <= s; i += 2) { // start from 3, stop at the square, increment in twos
      if(num % i === 0) return false; // modulo shows a divisor was found
  }
  return true;
}
console.log(isPrime(121));

Thanks to Zeph for fixing my mistakes.

Tomachi
  • 1,665
  • 1
  • 13
  • 15
  • 3
    Please add an explanation to your code. It helps people to understand the algorithm, so they can adapt it instead of just copying your code. – Mr. T Apr 15 '18 at 16:39
  • 2
    Fails on 9, as sqrt(9) = 3, and your loop does not get called. try `i <= s` – ZephDavies Jul 10 '19 at 18:17
13

Prime numbers are of the form 6f ± 1, excluding 2 and 3 where f is any integer

 function isPrime(number)
 { 
   if (number <= 1)
   return false;

   // The check for the number 2 and 3
   if (number <= 3)
   return true;

   if (number%2 == 0 || number%3 == 0)
   return false;

   for (var i=5; i*i<=number; i=i+6)
   {
      if (number%i == 0 || number%(i+2) == 0)
      return false;
   }

   return true;
 }

Time Complexity of the solution: O(sqrt(n))

H S W
  • 6,310
  • 4
  • 25
  • 36
9

Cool version:

const isPrime = n => ![...Array(n).keys()].slice(2).map(i => !(n%i)).includes(true) && ![0,1].includes(n)
Sergio
  • 1,370
  • 11
  • 12
8
function isPrimeNumber(n) {
  for (var i = 2; i < n; i++) { // i will always be less than the parameter so the condition below will never allow parameter to be divisible by itself ex. (7 % 7 = 0) which would return true
    if(n % i === 0) return false; // when parameter is divisible by i, it's not a prime number so return false
  }
  return n > 1; // otherwise it's a prime number so return true (it also must be greater than 1, reason for the n > 1 instead of true)
}

console.log(isPrimeNumber(1));  // returns false
console.log(isPrimeNumber(2));  // returns true
console.log(isPrimeNumber(9));  // returns false
console.log(isPrimeNumber(11)); // returns true
Marvel Moe
  • 825
  • 1
  • 6
  • 12
Mary Pieroszkiewicz
  • 363
  • 1
  • 5
  • 11
5

// A list prime numbers

function* Prime(number) { 
  const infinit = !number && number !== 0;
  const re = /^.?$|^(..+?)\1+$/;  
  let actual = 1;
 
  while (infinit || number-- ) {
      if(!re.test('1'.repeat(actual)) == true) yield actual;
      actual++
  };
};

let [...primers] = Prime(101); //Example
console.log(primers);
arius
  • 79
  • 1
  • 1
  • 4
    Very interesting solution, but I have no clue what is going on here (using a regex for generating a prime numbers sequence?) Can you give an explanation, please? – HynekS Nov 16 '18 at 11:17
  • 1
    https://iluxonchik.github.io/regular-expression-check-if-number-is-prime/ – ulou Apr 20 '21 at 17:26
5

I would do it like this:

const isPrime = (num) => num < 10 ? [2, 3, 5, 7].includes(num) : ![2, 3, 5, 7].some(i => !(num % i));

UPDATE (thx to @lakscastro):

export const isPrime = n => n <= 1 ? false : !Array.from(new Array(n), (el, i) => i + 1)
  .filter(x => x > 1 && x < n)
  .find(x => n % x === 0);
  • your answer is not correct, this has too many false positive cases. We have 168 prime numbers up to 1000, your function says we have 231 (test it from 0 to 1000 and you'll got 231 numbers) – Alex Rintt Apr 13 '22 at 23:48
4

I think this question is lacking a recursive solution:

// Preliminary screen to save our beloved CPUs from unneccessary labour

const isPrime = n => {
  if (n === 2 || n === 3) return true;
  if (n < 2 || n % 2 === 0) return false;

  return isPrimeRecursive(n);
}

// The recursive function itself, tail-call optimized.
// Iterate only over odd divisors (there's no point to iterate over even ones).
 
const isPrimeRecursive = (n, i = 3, limit = Math.floor(Math.sqrt(n))) => { 
  if (n % i === 0) return false;
  if (i >= limit) return true; // Heureka, we have a prime here!
  return isPrimeRecursive(n, i += 2, limit);
}

// Usage example

for (i = 0; i <= 50; i++) {
  console.log(`${i} is ${isPrime(i) ? `a` : `not a` } prime`);
}

This approach have it's downside – since browser engines are (written 11/2018) still not TC optimized, you'd probably get a literal stack overflow error if testing primes in order of tens lower hundreds of millions or higher (may vary, depends on an actual browser and free memory).

HynekS
  • 2,738
  • 1
  • 19
  • 34
3
function isPrime(num) {
    var prime = num != 1;
    for(var i=2; i<num; i++) {
        if(num % i == 0) {
            prime = false;
            break;
        }
    }
    return prime;
}

DEMO

Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • 4
    Instead of using for(var i=2; i < num; i++) you can use for (var i=2; i < Math.sqrt(num); i++) – creeperdomain Oct 23 '16 at 06:12
  • @ThomasW there's a good explanation of that here: https://stackoverflow.com/questions/5811151/why-do-we-check-up-to-the-square-root-of-a-prime-number-to-determine-if-it-is-pr – JohnnyQ Nov 29 '19 at 00:57
2

you can use below code in javascript for checking number is prime or not. It will reduce no of iteration and get the result fast.

function testPrime(num) {
        var isPrime = true;
        if (num >= 2) {
            if(num == 2 || num == 3){
               isPrime = true;
            }
            else if (num % 2 == 0) {
                isPrime = false;
            }
            else {
                for (i = 3; i <= Math.floor(Math.sqrt(num)); i += 2) {
                    if (num % i == 0) {
                        isPrime = false;
                        break;
                    }
                }
            }
        }
        else {
            isPrime = false;
        }
        return isPrime;
    }

//testPrime(21) false

2

very simple

const isPrime = num => {
  for (var i = 2; i < num; i++) if (num % i == 0) return false;
  return num >= 2; 
}
Behnam
  • 6,244
  • 1
  • 39
  • 36
2

One of the shortest version

isPrime=(n)=>[...Array(n-2)].map((_,i)=>i+2).filter(i=>n%i==0).length==0
1

I think a better way to find a prime number is with this logic:

var p=prompt("input numeric value","10"); // input your number 
for(j=2;j<p;j++){ 
  if(isPrimes(j)){ 
    document.write(j+", "); // for output the value
  } // end if
}// end for loop
function isPrimes(n) {
  var primes = true;// let prime is true
  for (i=2;i<n;i++) {
    if(n%i==0) {
      primes= false; // return prime is false
      break; // break the loop
    }// end if inner 
  }// end inner loop
  return primes; // return the prime true or false
}// end the function
thedp
  • 8,350
  • 16
  • 53
  • 95
1

You can try this one

function isPrime(num){
    
    // Less than or equal to 1 are not prime
    if (num<=1) return false;
    
    // 2 and 3 are prime, so no calculations
    if (num==2 || num==3 ) return true; 
    
    // If mod with square root is zero then its not prime 
    if (num % Math.sqrt(num)==0 ) return false;
    
    // Run loop till square root
    for(let i = 2, sqrt = Math.sqrt(num); i <= sqrt; i++) {
    
        // If mod is zero then its not prime
        if(num % i === 0) return false; 
    }
    
    // Otherwise the number is prime
    return true;
   }
   
   
   for(let i=-2; i <= 35; i++) { 
    console.log(`${i} is${isPrime(i) ? '' : ' not'} prime`);
   }
Nikhil Mahirrao
  • 3,547
  • 1
  • 25
  • 20
1

This answer is based on the answer by Ihor Sakaylyuk. But instead of checking for all numbers, I am checking only the odd numbers. Doing so I reduced the time complexity of the solution to O(sqrt(n)/2).

function isPrime(num) {
    if (num > 2 && num % 2 === 0) return false;
    for (var i = 3; i < Math.sqrt(num); i += 2) {
        if (num % i === 0) return false;
    }
    return num > 1;
}
Carson
  • 6,105
  • 2
  • 37
  • 45
vasanth.v
  • 235
  • 3
  • 14
1

Since Node.js 16, this is built-in:

import {checkPrimeSync as isPrime} from 'node:crypto';

console.log(isPrime(13));
//=> true

Otherwise, @IhorSakaylyuk's answer can be improved further by skipping even numbers:

function isPrime(number) {
    if((number % 2 === 0 && number !== 2) || number <= 1) {
        return false;
    }

    const limit = Math.floor(Math.sqrt(number));

    for(let index = 3; index <= limit; index += 2) {
        if (number % index === 0) {
            return false;
        }
    }

    return true;
}

I also created a npm package with this function.

Richie Bendall
  • 7,738
  • 4
  • 38
  • 58
1

Might be useful for some people: An implementation of the Miller Rabin primality test. Works for all positive integers less than Number.MAX_SAFE_INTEGER.

Try on JSFiddle: https://jsfiddle.net/4rxhas2o/


let unsafeToSquare = Math.floor(Math.sqrt(Number.MAX_SAFE_INTEGER))

function addMod(a, b, m) {
  // Returns (a + b) % m

  let sum = a + b

  let result = sum % m

  if (sum < Number.MAX_SAFE_INTEGER)
    return result

  let signature = ((a % 8) + (b % 8)) % 8

  let sumMod = sum % 8

  for (let i = -2; i <= 2; ++i) {
    if ((sumMod + i) % 8 === signature) {
      let ret = result + i

      if (ret > m)
        ret = (result - m) + i // prevent overflow

      return ret
    }
  }
}

function mulMod(a, b, m) {
  if (m === 0)
    return 0

  let prod = a * b

  if (prod < Number.MAX_SAFE_INTEGER)
    return prod % m

  let y = 0
  let result = a

  while (b > 1) {
    if (b % 2 === 0) {
      result = addMod(result, result, m)

      b /= 2
    } else {
      y = addMod(result, y, m)
      result = addMod(result, result, m)

      b = (b - 1) / 2
    }
  }

  return addMod(result, y, m)
}

function squareMod(b, m) {
  // Computes (b * b % m)

  return mulMod(b, b, m)
}

function expModLargeB(b, exponent, m) {
  let y = 1

  while (exponent > 1) {
    if (exponent % 2 === 0) {
      b = squareMod(b, m)

      exponent /= 2
    } else {
      y = mulMod(y, b, m)
      b = squareMod(b, m)

      exponent = (exponent - 1) / 2
    }
  }

  return mulMod(b, y, m)
}

function expMod(b, exponent, m) {
  if (exponent === 0)
    return 1

  if (b >= unsafeToSquare || m >= unsafeToSquare) {
    return expModLargeB(b, exponent, m)
  }

  let y = 1

  while (exponent > 1) {
    if (exponent % 2 === 0) {
      b *= b
      b %= m

      exponent /= 2
    } else {
      y *= b
      b *= b

      y %= m
      b %= m

      exponent = (exponent - 1) / 2
    }
  }

  return (b * y) % m
}

function _isProbablePrimeMillerRabin(p, base=2) {
  let pm1 = p - 1
  let pm1div = pm1
  let d, r = 0

  while (true) {
    if (pm1div % 2 === 0) {
      pm1div /= 2

      r++
    } else {
      d = pm1div
      break
    }
  }

  let x = expMod(base, d, p)

  if (x === 1 || x === pm1)
    return true

  for (let i = 0; i < r - 1; ++i) {
    x = squareMod(x, p)

    if (x === pm1)
      return true
  }

  return false
}

function _isPrimeLarge(p) {
  let bases

  if (p < 2047)
    bases = [2]
  else if (p < 1373653)
    bases = [2, 3]
  else if (p < 9080191)
    bases = [31, 73]
  else if (p < 25326001)
    bases = [2, 3, 5]
  else if (p < 3215031751)
    bases = [2, 3, 5, 7]
  else if (p < 4759123141)
    bases = [2, 7, 61]
  else if (p < 1122004669633)
    bases = [2, 13, 23, 1662803]
  else if (p < 2152302898747)
    bases = [2, 3, 5, 7, 11]
  else if (p < 3474749660383)
    bases = [2, 3, 5, 7, 11, 13]
  else if (p < 341550071728321)
    bases = [2, 3, 5, 7, 11, 13, 17]
  else
    bases = [2, 3, 5, 7, 11, 13, 17, 19, 23]


  return bases.every(base => _isProbablePrimeMillerRabin(p, base))
}

let smallPrimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223]

function isPrime(p) {
  if (!Number.isInteger(p) || p < 2)
    return false

  // Test for small primes
  for (let i = 0; i < smallPrimes.length; ++i) {
    let prime = smallPrimes[i]

    if (p === prime)
      return true
    if (p % prime === 0)
      return false
  }

  if (p <= 49729) { // 223*223
    return true;
  }
  else {
    return _isPrimeLarge(p)
  }
}


const tests = [1, 2, 3, 10, 100, 100019, 10000000019, 100000000003, 10000000000037]
let start = performance.now()

tests.forEach(test => {
    console.log(`${test} is ${ isPrime(test) ? "" : "not " }prime`)
})

let end = performance.now()
console.log("Tests completed in " + (end - start) + " ms.")
Ovinus Real
  • 528
  • 3
  • 10
  • You don't need the _isPrimeTrialDivision function, on numbers less than 150, with the test for small primes before you can tell that if the number is less than 49729 it is prime without having to do anything for (let i = 0; i < smallPrimes.length; ++i) { let prime = smallPrimes[i] if (p === prime) return true if (p % prime === 0) return false } if (p <= 49729) { // 223*223 return true; } else { return _isPrimeLarge(p) } – Roberto Alonso Gómez May 12 '22 at 01:41
1

The following implementation is faster than in all the previous answers, that's why I'm adding it.

The code below is from my prime library:

/**
 * Maximum prime number that can be generated in JavaScript,
 * using the standard 'number' type (53-bit of integer range).
 */
const maxPrime = 9_007_199_254_740_881;

const dividers = [
    0, 2, 6, 8, 12, 18, 20, 26, 30, 32, 36, 42, 48, 50, 56, 60, 62, 68, 72, 
    78, 86, 90, 92, 96, 98, 102, 110, 116, 120, 126, 128, 132, 138, 140, 146,
    152, 156, 158, 162, 168, 170, 176, 180, 182, 186, 188, 198, 200
];

function isPrime(x: number): boolean {
    if (isNaN(x) || x < 2 || x > maxPrime || x % 1) {
        return false;
    }
    if (x % 2 === 0) return x === 2;
    if (x % 3 === 0) return x === 3;
    if (x % 5 === 0) return x === 5;
    if (x % 7 === 0) return x === 7;
    const m = Math.sqrt(x);
    for (let i = 11; i <= m; i += 210) {
        for (const a of dividers) {
            if (x % (i + a) === 0) {
                return i + a === x;
            }
        }
    }
    return true;
}

On my machine, it can verify the first million numbers in 217ms.

vitaly-t
  • 24,279
  • 15
  • 116
  • 138
0

You are trying to check too much conditions. just one loop is required to check for a prime no.

function isPrime(num){
if(num==2) 
return true;
for(i=2;i<Math.sqrt(num);i++) // mathematical property-no number has both of its factors greater than the square root 
{
if(num % i==0) 
return false; // otherwise it's a prime no.
}
return true;
}

You have to consider every no. a prime no. unless it is divisible by some no. less than or equal to the square root.

Your solution has got a return statement for every case,thus it stops execution before it should.It doesn't check any number more than once.It gives wrong answer for multiple cases-- 15,35.. in fact for every no. that is odd.

DEVCNN
  • 614
  • 4
  • 13
0

It looks like your first if statement within the first 'if' statement within the for loop. Since if num = 9 and i = 2, 9 % i !== 0 but 9 is not prime since on the next iteration where i = 3, 9 % i === 0.

Here would be my answer to that question.

var isPrime = function(n) {
  if(typeof n !== 'number' || n <= 1 || n % 1 !== 0){
    return false;
  }
  for(var i = 2; i <= Math.sqrt(n); i += 1){
    if(n % i === 0){
      return false;
    }
  }
  return true;
};

The first if statement catches the edge cases. The for loop then checks from 2 up to the square root of n because of the mathematical property where no number has both of its factors greater than the square root of that number.

Hope this helps!

rodaan
  • 1
  • 1
0

This one is I think more efficient to check prime number :

function prime(num){
 if(num == 1) return true;
 var t = num / 2;
 var k = 2;
 while(k <= t) {
   if(num % k == 0) {
      return false
   } else {
   k++;  
  }
 }
  return true;
}
console.log(prime(37))
Himanshu Teotia
  • 2,126
  • 1
  • 27
  • 38
0

Simple version:

function isPrime(num) {
    if (num <= 1) { 
        return false;
    } else {
        for (var i = 2; i < num; i++) {
            if (num % i === 0) {
                return false; 
            }
        }
        return true;
    }  
}

console.log(isPrime(9));
Andy
  • 1,190
  • 1
  • 11
  • 25
  • it is totally wrong if you try with isPrime(9) return true and 9 is not prime! – Ezequiel De Simone Oct 27 '17 at 01:43
  • 1
    you are correct. I meant to place `i` and not 2 in the if statement `num % i === 0` the way it was, it was only dividing by 2 and not by every single number up to the number being evaluated. I just wanted a very simple way for beginners to understand this algorithm I have edited it :) – Andy Oct 27 '17 at 03:19
0

This is how I'd do it:

function isPrime(num) {
  if(num < 2) return false;
  if(num == 2) return true;
  for(var i = 2; i < num; i++) {
    if(num % i === 0) return false;
  }
  return true;
}
Harrison Kamau
  • 324
  • 1
  • 5
0
(function(value){
    var primeArray = [];
    for(var i = 2; i <= value; i++){ 
        if((i === 2) || (i === 3) || (i === 5) || (i === 7)){ 
            primeArray.push(i);
        }
          else if((i % 2 !== 0) && (i % 3 !== 0) && (i % 5 !== 0) && (i % 7 !== 0)){ 
              primeArray.push(i);
          }
        } 
       console.log(primeArray);
}(100));
tyroD
  • 1
0
function isAPrimeNumber(num){
     var counter = 0;
     //loop will go k equals to $num
     for (k = 1; k <= num; k++) {
      //check if the num is divisible by itself and 1
      // `%` modulus gives the reminder of the value, so if it gives the reminder `0` then it is divisible by the value
       if (num % k == 0) {
         //increment counter value 1
         counter  = counter  + 1;
        }
    }
   //if the value of the `counter is 2` then it is a `prime number`
  //A prime number is exactly divisible by 2 times only (itself and 1)
   if (counter == 2) {
     return num + ' is a Prime Number';
   }else{
    return num + ' is nota Prime Number';
   }
 }

Now call isAPrimeNumber() function by passing a value.

var resp = isAPrimeNumber(5);
console.log(resp);

Output:

5 is a Prime Number
Gufran Hasan
  • 8,910
  • 7
  • 38
  • 51
0
function isPrime(num) {
        if(num < 2) return false;
        for (var i = 2; i <= num/2; i++) {
            if(num%i==0)
                return false;
        }
        return true;
    }

If we want the prime number between two number we have to add this code only

for(var i = 0; i < 100; i++){
        if(isPrime(i))
            console.log(i);
    }
Srikrushna
  • 4,366
  • 2
  • 39
  • 46
0

Using Ticked solution Ihor Sakaylyuk

const isPrime = num => {
        for(let i = 2, s = Math.sqrt(num); i <= s; i++)
            if(num % i === 0) return false; 
        return num !== 1 && num !== 0;
}

Gives in console

isPrime( -100 ) true

const isPrime = num => {
  // if not is_number num return false

  if (num < 2) return false

  for(let i = 2, s = Math.sqrt(num); i <= s; i++) {
        if(num % i === 0) return false
  }

  return true
}

Gives in console

isPrime( 1 ) false

isPrime( 100 ) false

isPrime( -100 ) false

First 6 primes ? 2 3 5 7 11 13 ?

isPrime( 1 ) false

isPrime( 2 ) true // Prime 1

isPrime( 3 ) true // Prime 2

isPrime( 4 ) false

isPrime( 5 ) true // Prime 3

isPrime( 6 ) false

isPrime( 7 ) true // Prime 4

isPrime( 8 ) false

isPrime( 9 ) false

isPrime( 10 ) false

isPrime( 11 ) true // Prime 5

isPrime( 12 ) false

isPrime( 13 ) true // Prime 6

John Griffiths
  • 3,263
  • 4
  • 21
  • 19
0

function isPrime(n){
    if (isNaN(n) || !isFinite(n) || !Number.isInteger(n) || n<2) {
        return false;
    }

    if (n%2==0){
        return (n==2);
    }

    var sqrt = Math.sqrt(n);
    for (var i = 3; i < sqrt; i+=2) {
        if(n%i == 0){
            return false;
        }
    }
    
    return true;
}
ganesh phirke
  • 471
  • 1
  • 3
  • 12
0

My Solution,

function isPrimeNumber(number){
  if(number <= 1) return false;
  if(number <= 3) return true;
  for(let i = 2; i < 9; i++) {
    if(number === i) continue;
    if(number % i === 0 ) return false;
  }  
  return true;
}

for(let i = 0; i <= 100; i++){
  if (isPrimeNumber(i)) console.log(i);
}
VnoitKumar
  • 1,350
  • 15
  • 29
0

This calculates square differently and skips even numbers.

const isPrime = (n) => {
  if (n <= 1) return false;
  if (n === 2) return true;
  if (n % 2 === 0) return false;
  //goto square root of number
  for (let i = 3, s = n ** 0.5; i < s; i += 2) {
    if (n % i == 0) return false;
  }
  return true;
};
tsukimi
  • 1,605
  • 2
  • 21
  • 36
  • the numbers that are squares of primes are given as primes, I recommend a final comparison to identify those numbers if (n <= 1) return false; if (n === 2) return true; if (n % 2 === 0) return false; for (let i = 3, s = n ** 0.5; i < s; i += 2) { if (n % i == 0) return false; } return (n % Math.sqrt(n)!==0); – Roberto Alonso Gómez May 12 '22 at 01:56
0

This is a more reliable solution if you want to find n prime numbers.

function findPrime(n) {
      const primes = [];
      loop1:
      for (let j = 0; primes.length < n; j++) {
       loop2:
       for(let i = 2; i < j; i++){
        if(j % i === 0){
            continue loop1;
        }
      }
      if(j>1) primes.push(j);
      }
      console.log(primes);
    }
     
    findPrime(5);
RRD
  • 19
  • 1
  • 5
0
function isPrime(num) { 
  return Array.from({ length: num }, (i, index) => index + 1).filter(
    (item, i) => (num % item) === 0).length === 2;
}

function isPrime(num) { 
  return Array.from({ length: num }, (i, index) => index + 1).filter(
    (item, i) => (num % item) === 0).length === 2;
}

console.log(1, isPrime(1)); // false
console.log(2, isPrime(2)); // true
console.log(3, isPrime(3)); // true
console.log(4, isPrime(4)); // false
console.log(7, isPrime(7)); // true
console.log(96, isPrime(96)); // false
console.log(97, isPrime(97)); // true
console.log(98, isPrime(98)); // false
robert.batty
  • 490
  • 5
  • 13
0

Here is an optimized solution to prevent loop through all the range number.

  function isPrime(num) {
    for (let i = 2; i <= Math.sqrt(num); i++) {
      if (num % i == 0)
        return false;
    }
    return true;
  }
Ahmad Alsabbagh
  • 291
  • 3
  • 6
0

Three times faster then regular method:

function isPrime (num){
    if (num === 1){
        return false;
    }
    if(num === 2 || num === 3){
        return true;
    }
    if((num % 2 !== 0) && (num % 3 !== 0)){
        let k = 1;
        const numSqrt = Math.sqrt(num);
        if(( 6 * k - 1 ) > numSqrt){
            return true;
        } else {
            while( ( 6 * k - 1 ) <= numSqrt ){
                if(num % (6 * k - 1) !== 0 && num % (6 * k + 1) !== 0){
                return true;
            }
            k++;
        }
        return false;
      }
  }
  return false;
}
console.log(isPrime(29))

Nazariy
  • 408
  • 3
  • 10
0

We can find prime number up to n with only one loop, also I am increasing loop by +2:

function primeNumber(n) {
    let arr = [];
    if (n <= 1) return false;
    if (n === 2) return true;
    let flag = true;
    for (let i = 3; i < n; i += 2) {
        if (n % i == 0) {
            flag = false;
            break;
        }
    }
    return flag;
}
// It will retrun bollean true/false
// primeNumber(11)  true
// primeNumber(12)  false

Best part is complexity would be o(n/2)

ashish siddhu
  • 179
  • 4
  • 5
0

const checkPrime=(no)=>{
  var divisor = 2;

  while (no > divisor){
    if(no % divisor == 0){
     return `${no} is not a  prime no`; 
    }
    else
      divisor++;
  }
  return `${no} is a prime no`;
}
(console.log(checkPrime(3)));
(console.log(checkPrime(12)));
(console.log(checkPrime(233)));
Zaid Qureshi
  • 611
  • 10
  • 19
0
If x is not a prime, then we can find "a" and "b" such that
a**2 <= x <= b**2 , where a,b ∈ N+
=> a <= sqrt(x) <= b
So check until the sqrt(x) its upper bound is enough.

isPrime = x => {
    if (!Number.isInteger(x)) return false

    if (x > 2 && x % 2 ===0) return false 

    for (let divisor=3; divisor<=Math.sqrt(x); ++divisor) {
        if (x % divisor === 0) return false        
    }
    return x > 1
}

testData = [-1, 0, 1, 2, 3, 4, 4.1, 9, 11, "a"]
for (const data of testData) {
  console.log(`${data} is Prime? ${isPrime(data)}`)
}
Carson
  • 6,105
  • 2
  • 37
  • 45
0

this is a simple way i hope it helps :)

function isPrime(n) {
    if (n <= 1) return false;
    if (n === 2) return true;
    if (n % 2 === 0) return false;

    let arrayDis = [];

    for (let i = 1; i <= n; i++) {
        let count = n/i; 
        if (Number.isInteger(count)) arrayDis.push(count);
    }
      
    if(arrayDis.length > 2) return false
        
    return true;
}

console.log(isPrime(121)); // false
0

I barely understand people's code, so here is mine (idk if they are not too clean but i think it's very easy to understand)

    function primeNum (x){

//Array created for final checking
        const primeArray =[];
    
//Use for loop for filtering all possibility numbers that have 0 modulo

        for (var i = 1 ; i <= x ; i++){
            if (x % i === 0){
                primeArray.push(i)
            }
        }
    

//Check the primeArray use if statement

        if (primeArray.length === 2){
            return "it's a prime boys"
        } else {
            return "it's not a prime sorry to say"
        }
    }

the concept is simple, prime number is a number that only can divied by only 2 numbers and has modulo equal to 0 (x % i === 0). So if the primeArray has length more than 2 (more than 2 numbers), it's not a prime number.

i don't know what people says about my code, i need your advice guys. Best Regards.

wa1
  • 19
  • 4
  • Hi wa1. This is not the place to post code for review. Please only post code which is meant to be a solution for the problem described in the question at the top of this page. Ideally add some explanation of how the code works and why it solves the problem described in the question at the top of the page. The [tour] you took should have explained that concept and here are more details: [answer]. Otherwise welcome to StackOverflow and have fun. – Yunnosch Sep 11 '22 at 00:17
-1

This will cover all the possibility of a prime number . (order of the last 3 if statements is important)

   function isPrime(num){  
    if (num==0 || num==1) return false;
    if (num==2 || num==3 ) return true; 
    if (num % Math.sqrt(num)==0 ) return false;
    for (let i=2;i< Math.floor(Math.sqrt(num));i++) if ( num % i==0 ) return false;
    if ((num * num - 1) % 24 == 0) return true;        
   }
N.Tayel
  • 1
  • 1
-1

Following code uses most efficient way of looping to check if a given number is prime.

function checkPrime(number){    
    if (number==2 || number==3) {
    return true
}
    if(number<2 ||number % 2===0){
        return false
    }
    else{
        for (let index = 3; index <= Math.sqrt(number); index=index+2) {
            if (number%index===0) {
                return false
            }        
        }
    }
    return true
}
  1. First check rules out 2 and lesser numbers and all even numbers
  2. Using Math.sqrt() to minimize the looping count
  3. Incrementing loop counter by 2, skipping all even numbers, further reducing loop count by half
Suchin
  • 419
  • 5
  • 5
-1

The only even prime number is 2, so we should exclude even numbers from the loop.

function isPrime(a) {
    if (a < 2) return false;
    if (a > 2) {
        if (a % 2 == 0) return false;
        for (let x = 3; x <= Math.sqrt(a); x += 2) {
            if (a % x == 0) return false;
        }
    }
    return true;
}
Văn Quyết
  • 2,384
  • 14
  • 29
-1

BEST SOLUTION

I an unsure if I understand the concept of Time complexity: O(sqrt(n)) and Space complexity: O(1) in this context but the function prime(n) is probably the fastest way (least iterations) to calculate if a number is prime number of any size.

https://github.com/ganeshkbhat/fastprimenumbers, https://www.npmjs.com/package/fast-prime

This probably is the BEST solution in the internet as of today 11th March 2022. Feedback and usage is welcome.

This same code can be applied in any languages like C, C++, Go Lang, Java, .NET, Python, Rust, etc with the same logic and have performance benefits. It is pretty fast. I have not seen this implemented before and has been indigenously done.

If you are looking at the speed and performance here is the """BEST""" hopeful solution I can give:

Max iterations 16666 for n == 100000 instead of 100000 of conventional way

The codes can also be found here: https://github.com/ganeshkbhat/fastprimecalculations

If you use it for your project please spend 2 minutes of your time crediting me by letting me know by either sending me an email, or logging an Github issue with subject heading [User], or star my Github project. But let me know here https://github.com/ganeshkbhat/fastprimecalculations. I would love to know the fans and users of the code logic

function prime(n) {
    if ((n === 2 || n === 3 || n === 5 || n === 7)) {
        return true
    }
    if (n === 1 || ((n > 7) && (n % 5 == 0 || n % 7 == 0 || n % 2 == 0 || n % 3 == 0))) {
        return false
    }
    if ((Number.isInteger(((n - 1) / 6))) || (Number.isInteger((n + 1) / 6))) {
        for (let i = 1; i < n; i++) {
            let factorsix = (i * 6)
            let five = n / (5 + factorsix), seven = n / (7 + factorsix)
            if (((five > 1) && Number.isInteger(five)) || ((seven > 1) && (Number.isInteger(seven)))) {
                return false;
            }
            if (factorsix > n) {
                break;
            }
        }
        return true
    }
    return false
}

Here is an analysis of all the ways of calculation:

Conventional way of checking for prime:

function isPrimeConventionalWay(n) {
    count = 0
    // Corner case
    if (n <= 1)
        return false;
    // Check from 2 to n-1
    // Max iterations 99998 for n == 100000 
    for (let i = 2; i < n; i++) {
        // Counting Iterations
        count += 1
        if (n % i == 0) {
            console.log("count: Prime Conventional way", count)
            return false;
        }
    }
    console.log("count: Prime Conventional way", count)
    return true;
}

SQUAREROOT way of checking for prime:

function isPrimeSquareRootWay(num) {
    count = 0
    // if not is_number num return false
    if (num < 2) {
        console.log("count: Prime Squareroot way", count)
        return false
    }

    for (let i = 2, s = Math.sqrt(num); i <= s; i++) {
        // Counting Iterations
        count += 1
        if (num % i === 0) {
            console.log("count: Prime Squareroot way", count)
            return false
        }
    }
    console.log("count: Prime Squareroot way", count)
    return true
}

SUGGESTED way of checking for prime:

function prime(n) {
    let count = 0
    if ((n === 2 || n === 3 || n === 5 || n === 7)) {
        // console.log("count: Prime Unconventional way", count)
        return true
    }
    if (n === 1 || ((n > 7) && (n % 5 == 0 || n % 7 == 0 || n % 2 == 0 || n % 3 == 0))) {
        // console.log("count: Prime Unconventional way", count)
        return false
    }
    if ((Number.isInteger(((n - 1) / 6))) || (Number.isInteger((n + 1) / 6))) {
        for (let i = 1; i < n; i++) {
            // Counting Iterations
            count += 1
            let factorsix = (i * 6)
            let five = n / (5 + factorsix), seven = n / (7 + factorsix)
            if (((five > 1) && Number.isInteger(five)) || ((seven > 1) && (Number.isInteger(seven)))) {
                // console.log("count: Prime Unconventional way", count)
                return false;
            }
            if (factorsix > n) {
                // Max iterations 16666 for n == 100000 instead of 100000
                break;
            }
        }
        // console.log("count: Prime Unconventional way", count)
        return true
    }
    // console.log("count: Prime Unconventional way", count)
    return false
}
    

Tests to compare with the traditional way of checking for prime numbers.

    function test_primecalculations() {
            let count = 0, iterations = 100000;
            let arr = [];
            for (let i = 1; i <= iterations; i++) {
                let traditional = isPrimeConventionalWay(i), newer = prime(i);
                if (traditional == newer) {
                    count = count + 1
                } else {
                    arr.push([traditional, newer, i])
                }
            }
            console.log("[count, iterations, arr] list: ", count, iterations, arr)
            if (count === iterations) {
                return true;
            }
            return false;
        }
        
    console.log("Tests Passed: ", test_primecalculations())
    
    

You will see the results of count of number of iterations as below for check of prime number: 100007:

console.log("Is Prime 100007: ", isPrimeConventionalWay(100007))
console.log("Is Prime 100007: ", isPrimeSquareRootWay(100007))
console.log("Is Prime 100007: ", prime(100007))
count: Prime Conventional way 96
Is Prime 100007:  false
count: Prime Squareroot way 96
Is Prime 100007:  false
count: Prime Unconventional way 15
Is Prime 100007:  false

Performance Tests:

let iterations = 1000000;
let isPrimeConventionalWayArr = [], isPrimeSquarerootWayArr = [], primeArr = [], isprimeAKSWayArr = []
let performance = require('perf_hooks').performance;
// let performance = window.performance;

function tests_performance_isPrimeConventionalWayArr(){
    for (let i = 1; i <= iterations; i++){
        let start = performance.now()
        isPrimeConventionalWay(30000239)
        let end = performance.now()
        isPrimeConventionalWayArr.push(end - start)
    }
}
tests_performance_isPrimeConventionalWayArr()

function tests_performance_isPrimeSquarerootWayArr(){
    for (let i = 1; i <= iterations; i++){
        let start = performance.now()
        isPrimeSquarerootWay(30000239)
        let end = performance.now()
        isPrimeSquarerootWayArr.push(end - start)
    } 
}
tests_performance_isPrimeSquarerootWayArr()

function tests_performance_primeArr(){
    for (let i = 1; i <= iterations; i++){
        let start = performance.now()
        prime(30000239)
        let end = performance.now()
        primeArr.push(end - start)
    }
}
tests_performance_primeArr()


function calculateAverage(array) {
    var total = 0;
    var count = 0;
    array.forEach(function(item, index) {
        total += item;
        count++;
    });
    return total / count;
}

console.log("isPrimeConventionalWayArr: ", calculateAverage(isPrimeConventionalWayArr))
console.log("isPrimeSquarerootWayArr: ", calculateAverage(isPrimeSquarerootWayArr))
console.log("primeArr (suggested): ", calculateAverage(primeArr))

Sample 1 Million Iterations

Iteration 1:

isPrimeConventionalWayArr:  0.00011065770072489977
isPrimeSquarerootWayArr:  0.0001288754000402987
primeArr (suggested):  0.00005511959937214852
isPrimeSquarerootWayTwoArr:  0.00010504549999162554

Iteration 2:

isPrimeConventionalWayArr:  0.00011061320009082556
isPrimeSquarerootWayArr:  0.00012810260016098618
primeArr (suggested):  0.00005620509984344244
isPrimeSquarerootWayTwoArr:  0.00010411459982022643

Iteration 3:

isPrimeConventionalWayArr:  0.00010952920047193766
isPrimeSquarerootWayArr:  0.0001286292002275586
primeArr (suggested):  0.00005520999948307872
isPrimeSquarerootWayTwoArr:  0.00010410030033439397

Iteration 4:

isPrimeConventionalWayArr:  0.00011091169972717762
isPrimeSquarerootWayArr:  0.00012648080018162728
primeArr (suggested):  0.00005570890004560351
isPrimeSquarerootWayTwoArr:  0.00010492690009251237

Iteration 5:

isPrimeConventionalWayArr:  0.00010998740004003048
isPrimeSquarerootWayArr:  0.00012748069976270199
primeArr (suggested):  0.000060324400294572114
isPrimeSquarerootWayTwoArr:  0.00010445670029893518

Iteration 6:

isPrimeConventionalWayArr:  0.00011286130072548985
isPrimeSquarerootWayArr:  0.00012876759915798902
primeArr (suggested):  0.00005682649992406368
isPrimeSquarerootWayTwoArr:  0.0001073473998978734

Iteration 7:

isPrimeConventionalWayArr:  0.0001092233005464077
isPrimeSquarerootWayArr:  0.0001272089005112648
primeArr (suggested):  0.00006196610003709793
isPrimeSquarerootWayTwoArr:  0.000105714200142771

Iteration 8:

isPrimeConventionalWayArr:  0.00010890220178663731
isPrimeSquarerootWayArr:  0.00012892659988626836
primeArr (suggested):  0.000055275400444865224
isPrimeSquarerootWayTwoArr:  0.00010486920177191496

Iteration 9:

isPrimeConventionalWayArr:  0.00011153739924356342
isPrimeSquarerootWayArr:  0.00012576029987260699
primeArr (suggested):  0.00005680049995332956
isPrimeSquarerootWayTwoArr:  0.00010467480102181434

Iteration 10:

isPrimeConventionalWayArr:  0.00011035799815505743
isPrimeSquarerootWayArr:  0.0001265768006257713
primeArr (suggested):  0.00005575320014730096
isPrimeSquarerootWayTwoArr:  0.00010596680009737611

Sample 10 Million (10000000) Iterations

Iteration 1:

isPrimeConventionalWayArr:  0.00011928780986890197
isPrimeSquarerootWayArr:  0.00012412049009799956
primeArr (suggested):  0.00005793778010234237
isPrimeSquarerootWayTwoArr:  0.00010363322006165981

Iteration 2:

isPrimeConventionalWayArr:  0.00010635640006065368
isPrimeSquarerootWayArr:  0.00012505082993544638
primeArr (suggested):  0.000053171040023490784
isPrimeSquarerootWayTwoArr:  0.00010545557955764234

Iteration 3:

isPrimeConventionalWayArr:  0.00010894328009858727
isPrimeSquarerootWayArr:  0.00012658657005652784
primeArr (suggested):  0.00005493023999705911
isPrimeSquarerootWayTwoArr:  0.00010782274951003491

JSFiddle Link as example:

https://jsfiddle.net/ganeshsurfs/y683v5s2/ Results I used to get for 10 Million iterations are as below:

Iteration 1:

"isPrimeConventionalWayArr: ", 0.0002012
"isPrimeSquarerootWayArr: ", 0.0002838
"primeArr (suggested): ", 0.0002132
"isPrimeSquarerootWayTwoArr: ", 0.0002189

Iteration 2:

"isPrimeConventionalWayArr: ", 0.0002242
"isPrimeSquarerootWayArr: ", 0.0002486
"primeArr (suggested): ", 0.000181
"isPrimeSquarerootWayTwoArr: ", 0.0002145
Gary
  • 2,293
  • 2
  • 25
  • 47
  • This is sluggish as hell for being a best solution. Counting primes between 1 and 300000 (there are 25997 of them) takes 150 times longer than the simple approach with `sqrt()`. 3000ms vs 20ms on my machine. Even using `Number.isInteger(num/i)` instead of `num % i ===0` makes the `sqrt()` approach running for 30ms, which is still 100-times faster. – tevemadar Mar 11 '22 at 11:47
  • @tevemadar Yes, true possible. Can you check the performance and put it here. I would also like to inform all the people using this. I saw more iterations even in Squareroot `sqrt()` way than the way mentioned by me. You can check the iteration differences. That it self solves most problems of performance and makes this faster than most solutions. `Please recheck` – Gary Mar 11 '22 at 12:23
  • @tevemadar Check this out: `print("Is Prime 30000239 : ", isPrimeConventionalWay(30000239)) ----- print("Is Prime 30000239 : ", isPrimeSquarerootWay(30000239)) ----- print("Is Prime 30000239 : ", prime(30000239)) ----- print("Is Prime 30000239 : ", isprimeAKSWay(30000239))` result is as follows – Gary Mar 11 '22 at 12:35
  • @tevemadar `count: Prime Conventional way 28 Is Prime 30000239 : False --- count: Prime Squareroot way 28 Is Prime 30000239 : False --- count: Prime Unconventional way 4 Is Prime 30000239 : False --- count: Prime AKS -Mersenne primes - Fermat's little theorem or whatever way 9 Is Prime 30000239: False` – Gary Mar 11 '22 at 12:36
  • Check the python code for the AKS implementation https://stackoverflow.com/a/71438297/3204942 – Gary Mar 11 '22 at 12:37
  • https://jsfiddle.net/tevemadar/c63k7bye/ (runs until 100000 only, so completes faster, the speed difference is still very visible) – tevemadar Mar 11 '22 at 14:19
  • I am unsure how that is so different. I am updating with the performance tests in the answer now. – Gary Mar 11 '22 at 16:06
  • @tevemadar I have updated with the tests in jsfiddle now. You can check this out. Updated the post. https://jsfiddle.net/ganeshsurfs/y683v5s2/ Can you now remove your down vote now – Gary Mar 11 '22 at 16:28
-2

Why are you trying to use loops!? Iterating is such a waste of computing power here...

This can be done using math:

function isPrime(num) {
    if ( num !=1 && num%3 != 0 && num%5 != 0 && num%7 != 0 && num%9 != 0 && num%11 != 0 && Math.sign(num) == 1 && Math.round(num) == num) {

        if ( (num-1)%6 == 0 || (num+1)%6 == 0 ) {
            return true;
        }

    } // no need for else statement since if true, then will do return
    return num==11||x==9||num==5||num==3||num==2; // will return T/F;
}

Steps:

  1. Check if the number is divisible by 5 (evenly)
  2. Check if the number is positive (negative numbers are not prime)
  3. Check if the number is a whole number (5.236 by rule not prime)
  4. Check if the number ± 1 is divisible by 6 (evenly)
    For more information check out 3Blue1Brown's Video
  5. Check if the number is 2, 3, 9 or 11 (outliers with the rule)
  6. Check if the number is 7 or 5 (due to attempt at false-positive reduction)

Always try to do the mathematical way, rather than iterating over loops. Math is almost always the most efficient way to do something. Yes, this equation might be confusing... However, we don't need much readability when it comes to checking if something is prime or not... It likely isn't going to need to be maintained by future code editors.

EDIT:
Optimized code version:

function isPrime(x=0) {
    const m = Math;
    return (x%3!=0&&x%5!=0&&x%7!=0&&x%9!=0&&x%11!=0&&x!=1&&m.sign(x)*m.round(x)==x&&(!!!((x-1)%6)||!!!((x+1)%6)))||x==11||x==9||x==7||x==5||x==3||x==2;
}

EDIT:
As it turns out... there's more to do with false-positive detection, because they're randomly distributed (at least seemingly) so the +-1 %6 stuff really isn't going to work for everything... But I'm definitely on to something here...

255.tar.xz
  • 700
  • 7
  • 23
  • 1
    2 3 and 5 are prime numbers, but your function returns false. – Seblor Nov 23 '19 at 18:36
  • 1
    @Seblor I've fixed that part for now... But as you can see in the second edit there are other issues that I ran into and don't really know how to solve without iteration... So I'm close, but no cigar... Anyway, hope this inspires someone savvier with math to come up with something incredible... But for now... This is just a dying prototype... LOL – 255.tar.xz Nov 23 '19 at 19:37
  • 1
    There are infinitely many primes ... You can catch a load of non-primes with your code, but you're definitely going to need a loop for the big boys. – MrWatson Jan 30 '20 at 13:25
-3

i think the easiest way to get it and faster is

function isPrime(num) {
  for(var i = 2; i < Math.sqrt(num); i++) {
      if(num % i === 0){
          return false;
       } 
  return num > 1; 
  }
}

console.log(isPrime(9))
Tochukwu Ogugua
  • 111
  • 1
  • 2
  • 9
-4

One line solution Using ternary '?' operator

const primeNum = (num = 1) => num < 2 ? 'Not a prime number' : (num === 2 || num % 2 !== 0) ? 'Prime number' : 'Not a prime number'

console.log(primeNum())
console.log(primeNum(0))
console.log(primeNum(2))
console.log(primeNum(3))