Home  >  Article  >  Web Front-end  >  How to find prime numbers in an array in JavaScript

How to find prime numbers in an array in JavaScript

青灯夜游
青灯夜游Original
2021-09-02 16:02:534173browse

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.

How to find prime numbers in an array in JavaScript

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])
	}
}

How to find prime numbers in an array in JavaScript

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

How to find prime numbers in an array in JavaScript

[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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn