search
HomeWeb Front-endJS TutorialHow to find prime numbers in javascript

How to find prime numbers in javascript

Sep 20, 2022 am 11:59 AM
javascriptprime number

How to find prime numbers: 1. Traverse all natural numbers in the range 1~n and divide by n. If the remainder is 0, it means that the number n is not a prime number, otherwise it is a prime number. The syntax "for(i=2 ;i

How to find prime numbers in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

The concept of prime numbers

Prime numbers are also called prime numbers. A prime number refers to a number that is not divisible by other natural numbers except 1 and itself among the natural numbers greater than 1. .

Prime numbers within 100: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71 , 73, 79, 83, 89, 97, 25 in total.

Four ways to determine prime numbers using JavaScript

1. Prime numbers can only be divisible by 1 and itself

Prime numbers can only It is divisible by 1 and itself, so all natural numbers in the open interval (1, n) are traversed and divided by n. If there is an integer division, that is, the remainder is 0, it means that the number n is not a prime number, otherwise it is a prime number.

function isPrime(n) {
  n = parseInt(n);
 
  if (n  1;
  }
 
  for (let i = 2; i <p>But the complexity of this algorithm is O(n)</p><h3 id="strong-The-range-of-square-roots-of-prime-numbers-strong"><strong>2. The range of square roots of prime numbers</strong></h3><p>Assuming n is not a prime number, then n except It can be divided not only by 1 and n, but also by i and j, that is, n / i = j...0, for example, 15 is not a prime number, 15 / 3 = 5, for example, 35 is not a prime number, 35 / 5 = 7, this When i and j must be in (1, Math.sqrt(n)] and [Math.sqrt(n), n) respectively, for example, Math.sqrt(15) ≈ 3.8, then 3 is in (1, 3.8], 5 is in [3.8, 15). For example, Math.sqrt(4) = 2, then 2 is in (1,2] and also in [2,4). </p><pre class="brush:php;toolbar:false">function isPrime(n) {
  n = parseInt(n);
 
  if (n  1;
  }
 
  for (let i = 2; i <p>The complexity of the algorithm at this time is O(sqrt(n))</p><h3 id="strong-The-prime-number-cannot-be-any-other-even-number-other-than-strong"><strong>3. The prime number cannot be any other even number other than 2</strong></h3><p>Except 2, All even numbers are not prime numbers</p><p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/image/644/149/762/1663645614907138.png?x-oss-process=image/resize,p_40" class="lazy" title="1663645614907138.png" alt="How to find prime numbers in javascript"></p><pre class="brush:php;toolbar:false">function isPrime(n) {
  n = parseInt(n);
 
  if (n  1;
  }
 
  if (n % 2 === 0) {
    return false;
  }
 
  for (let i = 3; i <p>n in the for loop can only be the light blue part of the picture above. </p><p> Therefore, the above algorithm reduces the loop by half, and the time complexity is O(sqrt(n) / 2) </p><p>It should be noted that the code of this algorithm cannot be n % 2 == The judgment condition of = 0 is added to the loop. There is a loophole in the following code. </p><pre class="brush:php;toolbar:false">function isPrime(n) {
  n = parseInt(n);
 
  if (n  1;
  }
 
  for (let i = 3; i <p>At this time, 4, 6, and 8 will all be judged as prime numbers. </p><p>The reason for the vulnerability is that the loop condition i </p><p>This algorithm can only ensure that the n value of n when the loop condition i = i^2 = 9. </p><h3 id="strong-Prime-numbers-greater-than-or-equal-to-must-be-adjacent-to-multiples-of-strong"><strong>4. Prime numbers greater than or equal to 5 must be adjacent to multiples of 6</strong></h3><p>Prime numbers greater than or equal to 5 must be adjacent to multiples of 6</p><p> (Note that this sentence is not equivalent to: Numbers adjacent to <span style="text-decoration:line-through;"> and multiples of 6 must be prime numbers </span> greater than 5. This conclusion is not true.) </p><p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/image/674/593/865/1663645632699688.png?x-oss-process=image/resize,p_40" class="lazy" title="166364562667908How to find prime numbers in javascript" alt="How to find prime numbers in javascript"></p><p>As shown in the picture above, numbers greater than or equal to 5 are divided into: 6y-1, 6y, 6y 1, 6y 2, 6y 3, 6y 4 (y>=1)</p><p>Among them, 6y, 6y 2 , 6y 3, and 6y 4 cannot be prime numbers. Only 6y-1 and 6y 1<strong><span   style="max-width:90%">may</span></strong> are prime numbers. </p><p>In addition, 6y-1 (y>=1) and 6y 5 (y>=0) are equivalent. </p><p>So, we can directly exclude the numbers where n is not 6y-1 (or 6y 5) and 6y 1. The elimination method is, </p><pre class='brush:php;toolbar:false;'>  if (n % 6 !== 1 && n % 6 !== 5) {
    return false;
  }

Next, we need to eliminate 6y-1 (or The non-prime numbers in 6y 5) and 6y 1,

  for (let i = 5; i <= Math.sqrt(n); i += 6) {
    if (n % i === 0 || n % (i + 2) === 0) {
      return false;
    }
  }

There may be two things you are confused about here:

  • Why is the increment of i in the for loop 6
  • Why is the condition for prime number determination in the for loop n % i === 0 || n % (i 2) === 0

How to find prime numbers in javascript

Looking at the above diagram, we can find that 6y-1 is an arithmetic sequence with a base of 5 and a difference of 6, that is, 5 6x:

  • 对于 5 + 6x 而言,如果x为5的倍数(5 * z),则5 + 6x = 5 + 6 * 5 * z = 5 *(1+6z),则此时5 + 6x可以被5整除
  • 5 + 6x 还可以转化为 5 + 6 + 6 * (x-1) = 11 + 6(x-1),则只要x-1为11的倍数,则5 + 6x可以被11整除
  • 5 + 6x 还可以转化为 5 + 12 + 6 * (x-2) = 17 + 6(x-2),则只要x-2为17的倍数,则5 + 6x可以被17整除
  • ......

6y+1,是基数为7,差值为6的等差数列,即 7 + 6x :

  • 对于 7 + 6x 而言,如果x为7的倍数(7 * z),则7 + 6x = 7 + 6 * 7 * z = 7 *(1+6z),则此时7 + 6x可以被7整除
  • 7 + 6x 还可以转化为 7 + 6 + 6 * (x-1) = 13 + 6(x-1),则只要x-1为13的倍数,则7 + 6x可以被13整除
  • 7 + 6x 还可以转化为 7 + 12 + 6 * (x-2) = 19 + 6(x-2),则只要x-2为19的倍数,则7 + 6x可以被19整除
  • ......

所以6y-1和6y+1可能整除的数自增量为6,这是for循环i自增为啥是 6的原因

且6y-1和6y+1的整除数基数为5和7,相差为2,这是for循环中素数判定的条件为啥是 n % i === 0 || n % (i+2) === 0的原因

function isPrime(n) {
  n = parseInt(n);
 
  if (n  1;
  }
 
  if (n % 6 !== 1 && n % 6 !== 5) {
    return false;
  }
 
  for (let i = 5; i <p>此时时间复杂度为 O(sqrt(n) / 3) <br></p><p>【相关推荐:<a href="https://www.php.cn/course/list/17.html" target="_blank" textvalue="javascript视频教程">javascript视频教程</a>、<a href="https://www.php.cn/course/list/91.html" target="_blank" textvalue="编程基础视频">编程基础视频</a>】</p>

The above is the detailed content of How to find prime numbers 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
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

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 Article

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Atom editor mac version download

Atom editor mac version download

The most popular open source editor