JS Example Tutorial: Using 6n±1 method to calculate prime numbers

Source: Internet
Author: User

Using 6n±1 method to calculate prime number
Any natural number can always be expressed as one of the following forms:
6n,6n+1,6n+2,6n+3,6n+4,6n+5 (n=0,1,2, ...)
Obviously, when the n≥1, 6n,6n+2,6n+3,6n+4 are not prime, only the shape such as 6n+1 and 6n+5 natural numbers are likely to be prime. So, except for 2 and 3, all primes can be represented as 6n±1 (n is the natural number).
According to the above analysis, we can construct the other side sieve, only to the shape such as 6 n±1 natural number screening, so can greatly reduce the number of screening, so as to further improve the operating efficiency and speed of the program.

The following code requires a natural number greater than 10
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));

Do you have any more efficient methods or the above code has the wrong place, please point out.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.