Method: Use the for loop statement or filter() method to loop through the array, and in each loop, remove an array element by 2 to "sqrt (the element itself)". If it can be divided, it means that the The array element is not a prime number, otherwise it is a prime number; if the array element is a prime number, just output the element.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
What are prime numbers?
Prime numbers, also known as prime numbers, refer to natural numbers greater than 1 that have no other factors except 1 and itself.
How to find the prime number in an array in JavaScript
Use the for loop statement or filter() method to loop through the array and judge in each loop Whether an array element is a prime number, if so, output the element.
How to determine whether it is a prime number: Use a number to divide 2 to sqrt (this number) respectively. If it can be divided evenly, it means that the number is not a prime number, otherwise it is a prime number.
Let’s take a look at the implementation method:
Use for loop
var a = [31,33,35,37,39,41,43,45,57,49,51,53]; for(var i=0;i<a.length;i++){ var flag = 1; for(var j = 2; j*j <= i; j++) {//能被2 - sqrt(i)整除的数 if(a[i] % a[j] == 0) { flag = 0; break; } } if(flag == 1) { console.log(a[i]) } }
Use filter() Method
function f(value, index, ar) { high = Math.floor(Math.sqrt(value)) + 1; for (var div = 2; div <= high; div++) { if (value % div == 0) { return false; } return true; } } var a = [31, 33, 35, 37, 39, 41, 43, 45, 57, 49, 51, 53]; var a1 = a.filter(f); console.log(a1);
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to find prime numbers in an array in JavaScript. For more information, please follow other related articles on the PHP Chinese website!