Home > Web Front-end > JS Tutorial > JS Use 6N±1 Method to Find Prime Numbers Example Tutorial_Javascript Skills

JS Use 6N±1 Method to Find Prime Numbers Example Tutorial_Javascript Skills

WBOY
Release: 2016-05-16 18:44:03
Original
981 people have browsed it

Use the 6N±1 method to find prime numbers
Any natural number can always be expressed in one of the following forms:
6N, 6N 1, 6N 2, 6N 3, 6N 4, 6N 5 (N=0, 1, 2,...)
Obviously, when N≥1, 6N, 6N 2, 6N 3, 6N 4 are not prime numbers. Only natural numbers in the form of 6N 1 and 6N 5 may be prime numbers. Therefore, except for 2 and 3, all prime numbers can be expressed in the form of 6N±1 (N is a natural number).
Based on the above analysis, we can construct another sieve to screen only natural numbers in the shape of 6 N±1. This can greatly reduce the number of screenings and further improve the operating efficiency and speed of the program.
The following code requires a natural number greater than 10

Copy code The code is as follows:

function fn( num){
var arr = [];
arr.push(2);
arr.push(3);
arr.push(5);
arr.push(7 );
var t = 0;
for (var i = 3; t < num; i = i 3) {
for (var j = 0; j < 2; j ) {
t = 2 * (i j) - 1;
if (t < num && (t % 5 == 0 ? false : t % 7 == 0 ? false : true)) {
arr. push(t);
}
}
}
return arr.join(” “);
}
document.write(fn(1000));

If you guys have any more efficient methods or if there is something wrong with the above code, please point it out.
Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template