Home  >  Article  >  Web Front-end  >  JavaScript implementation code sharing for finding prime numbers within a specified range

JavaScript implementation code sharing for finding prime numbers within a specified range

黄舟
黄舟Original
2017-03-18 14:51:082341browse

A prime number is a natural number greater than 1 that has no other factors except 1 and itself.

This post will consider how to find prime numbers within a specified range.

ImplementationFunction has the following characteristics:

1.It accepts 2 parameters, representing two boundaries, such as getPrimes(0, 30), means to find all the items between 0 and 30 prime numbers.

2.The first of the two parameters can be larger than the second, such as getPrimes(30, 0), which still represents the request## All prime numbers between #0 to 30.

3. Both boundary values ​​are within the considered range.

4. The return value is an increasing

array, which contains all prime numbers in the range.

The idea of ​​​​the problem:

1. First, we need a method to determine prime numbers.

2. Process the parameters and determine the upper and lower boundaries.

3. Carry out sequential traversal within the range, and store prime numbers in the array.

Code implementation:

//判断是否为质数
function isPrime(number) {
	//0,1,负数肯定不是
    if(number < 2){
        return false;
    }
    var factor = Math.sqrt(number);
	//注意:这里是"<=factor",而不是"<"
	//比如说25,factor是5,如果用"<"就会误判
    for(var i=2;i<=factor;i++){
        if(number % i == 0){
            return false;
        }
    }
    return true;
}

//获取范围内的质数
function getPrimes(start, finish) {
	//确定上边界
    var max = Math.max(start, finish);
	//确定下边界
    var min = Math.min(start, finish);
    var result = [];
	//由小到大遍历
    for(var i=min;i<=max;i++){
		//满足质数条件,存入数组
        if(isPrime(i)){
            result.push(i);
        }
    }
    return result;
}

//[]
console.log(getPrimes(0, 0)); 
//[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
console.log(getPrimes(0, 30));
//[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
console.log(getPrimes(30, 0));

The above is the detailed content of JavaScript implementation code sharing for finding prime numbers within a specified range. 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