Blog

Determine If a Positive Integer is a Prime Number Using JavaScript
Posted on November 27, 2017 in Algorithms, JavaScript by Matt Jennings

function getPrimeNumber(num) { 

  var arr = [];
  
  for(var i = 1; i < num + 1; i++) {
     if(num === 1) {
       return false;
     }
     else if(num % i === 0) {
       arr.push(i);
     }
    
  }
  
  if( arr.length > 2 ) {
    return false
  }
  else if(arr.length === 2) {
    return true;
  }
         
}

// Output is true because 19 is a prime number
console.log(getPrimeNumber(19));

Leave a Reply