isPrime

isPrime

Prime Number is a number that can evenly divide by itself or one.


##For Example console.log(isPrime(8)) false console.log(isPrime(11)) true console.log(isPrime(121)) false console.log(isPrime(127)) true ##


function isPrime(num) {
  
  if (num < 2) {
    return false;
  }
  
  // modulus %
  for (let i = 2; i < num; i++) {
    if (num % i === 0) {
      return false;
    }
  }
  return true;
}

console.log(isPrime(8))
console.log(isPrime(11))
console.log(isPrime(121))
console.log(isPrime(127))



In order to solve the prime number checker we first create a function in our case function isPrime(num) We know that prime numbers are numbers that are divisible by themself or by one so next logical step is who is our first prime number and that is number 2.
We create if statement checking if(num < 2){ return false } so if the number provided as a parameter is less than 2 is false since 1 is divisible only by 1.
Next in our journey we need the MODULUS operator, we create a function
for(let i = 2; i < num; i++ ){ if (num % i === 0) { return false; } } So we created a loop that goes from 2 to the one number less than the parameter and inside that loop we check if number divisible by the loop (2, 3, 4, 5, etc..) is equal to 0 than we return false
Because if number is divisible by any loop counter and equal to 0 than that number is not prime that is why we return false.
In any other case we return true designated by return true after the for loop

comments powered by Disqus