Number Prime Test in JavaScript

Check Number prime in JavaScript

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;
}

Javascript prime number check

You should avoid the else case and return only after for loop completion. Although for loop count can be reduced by updating condition to i <= Math.sqrt(num) ( as @PatrickRoberts suggested ).

function isPrime(num) {
if (num <= 1) return false;
if (num === 2) return true;

// storing the calculated value would be much
// better than calculating in each iteration
var sqrt = Math.sqrt(num);

for (var i = 2; i <= sqrt; i++)
if (num % i === 0) return false;
return true;
}

FYI : In your code on the first iteration of the loop num % i === 0(9 % 2) would be false and it would return the else statement(true).

Shortest way to get prime numbers JS

Referring the great answer of @Sergio to the question: Number prime test in JavaScript. You can filter the prime numbers in the array then get the largest one by using the Math.max function.

let arr1 = [1,5,7,6,9,10,13,11,12]
function largestPrime(arr) {
return Math.max(...arr.filter((n) => { return ![...Array(n).keys()].slice(2).map(i => !(n%i)).includes(true) && ![0,1].includes(n) }));
}
console.log(largestPrime(arr1));

isPrime Function - check if that num is a Prime Number or not - Javascript

You can loop to check if the number is divisible by any integer from 2 to the square root of the number. If not, the number is prime.

let insertedValue = +prompt("enter your value" , "");
const isPrime = (num) => {
if(num <= 1) return false;
for(let i = 2; i * i <= num; i++)
if(num % i === 0) return false;
return true;
}
alert(isPrime(insertedValue) ? `${insertedValue} is a prime number`
: `${insertedValue} isn't a prime number`);


Related Topics



Leave a reply



Submit