isPrime-v2
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;
}
let root = Math.ceil(Math.sqrt(num))
console.log(root) // 3 , 4 , 11 , 12
for (let i = 2; i <= root; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
console.log(isPrime(8)) Math.ceil(Math.sqrt(8)) => 3
console.log(isPrime(11)) Math.ceil(Math.sqrt(11)) => 4
console.log(isPrime(121)) Math.ceil(Math.sqrt(121)) => 11
console.log(isPrime(127)) Math.ceil(Math.sqrt(127)) => 12
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.
In order to divide our work and computation we use Math.sqrt which returns the square root of a number but in order to round it we use the Math.ceil function provided by javascript.
What is Math.ceil well MDN definition is The Math.ceil() function always rounds a number up to the next largest integer.
So we write the root in a variable then round it and take the square root of the number that is something like this let root = Math.ceil(Math.sqrt(num))
Next in our journey we need the MODULUS operator, we create a function
for(let i = 2; i <= root; i++ ){
if (num % i === 0) {
return false;
}
}
So we created a loop that goes from 2 to the root number 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