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
JavaScript Filter Array of Objects
Display Posts in Descending Posted Order
What Does (Function($) {})(Jquery); Mean
Javascript/Jquery: $(Window).Resize How to Fire After the Resize Is Completed
Callback After All Asynchronous Foreach Callbacks Are Completed
Access Control Request Headers, Is Added to Header in Ajax Request with Jquery
Convert Utc Epoch to Local Date
How to Create a Dynamic Key to Be Added to a JavaScript Object Variable
How to Iterate Through Table Rows and Cells in JavaScript
JavaScript Scroll Event for Iphone/Ipad
Using JavaScript's Atob to Decode Base64 Doesn't Properly Decode Utf-8 Strings
Handling Errors in Promise.All
Declaring Multiple Variables in JavaScript
How to Check If a String Contains Text from an Array of Substrings in JavaScript
Why Does the Month Argument Range from 0 to 11 in JavaScript's Date Constructor