JS algorithms #2 — Prime number.

Simuratli
1 min readJan 10, 2024

Given a number n, let’s determine whether this number is prime or not. A prime number is a natural number greater than 1 that is not the product of two smaller natural numbers. For example:

isPrime(5) = true because (1*5 and 5*1)

isPrime(4) = false because (1*4 , 2*2 and 4*1)

const isPrime = (n) => {
if(n <= 1) return false
for (let i = 2; i<n; i++){
if(n%i === 0){
return false
}
}
return true
}

console.log(isPrime(5)) //true
console.log(isPrime(1)) //false
console.log(isPrime(4)) //false

Integers larger than the square root do not need to be checked because whenever n=a×b, one of the two factors, a or b, is less than or equal to the square root of n.

const isPrime = (n) => {
if(n <= 1) return false
for (let i = 2; i<= Math.sqrt(n); i++){
if(n%i === 0){
return false
}
}
return true
}

console.log(isPrime(5)) //true
console.log(isPrime(1)) //false
console.log(isPrime(4)) //false

--

--

Simuratli

MSc. High Energy and Plasma Physics | B.A. Computer Engineering | Content Creator