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

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

Mar 18, 2017 pm 02:51 PM

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));
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

How to build an AI-oriented data governance system? How to build an AI-oriented data governance system? Apr 12, 2024 pm 02:31 PM

In recent years, with the emergence of new technology models, the polishing of the value of application scenarios in various industries and the improvement of product effects due to the accumulation of massive data, artificial intelligence applications have radiated from fields such as consumption and the Internet to traditional industries such as manufacturing, energy, and electricity. The maturity of artificial intelligence technology and application in enterprises in various industries in the main links of economic production activities such as design, procurement, production, management, and sales is constantly improving, accelerating the implementation and coverage of artificial intelligence in all links, and gradually integrating it with the main business , in order to improve industrial status or optimize operating efficiency, and further expand its own advantages. The large-scale implementation of innovative applications of artificial intelligence technology has promoted the vigorous development of the big data intelligence market, and also injected market vitality into the underlying data governance services. With big data, cloud computing and computing

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

What does prime mean in c++ What does prime mean in c++ May 07, 2024 pm 11:33 PM

prime is a keyword in C++, indicating the prime number type, which can only be divided by 1 and itself. It is used as a Boolean type to indicate whether the given value is a prime number. If it is a prime number, it is true, otherwise it is false.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

What does prime mean in c++ What does prime mean in c++ May 07, 2024 pm 11:24 PM

In C++, prime refers to a prime number, a natural number that is greater than 1 and is only divisible by 1 and itself. Prime numbers are widely used in cryptography, mathematical problems and algorithms. Methods for generating prime numbers include Eratostheian sieve, Fermat's Little Theorem, and the Miller-Rabin test. The C++ standard library provides the isPrime function to determine whether it is a prime number, the nextPrime function returns the smallest prime number greater than a given value, and the prevPrime function returns the smallest prime number less than a given value.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

See all articles