How to calculate prime numbers using the 6N & #177; 1 method in JS

Source: Internet
Author: User

Evaluate the prime number using the 6N ± 1 Method
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 N is ≥1, 6N, 6N + 2, 6N + 3, 6N + 4 are not prime numbers, only the natural numbers such as 6N + 1 and 6N + 5 may be prime numbers. Therefore, all prime numbers except 2 and 3 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 filter the natural numbers such as 6 N ± 1, which can greatly reduce the number of screening times, this further improves the program running efficiency and speed.
The following code requires a natural number greater than 10
Copy codeThe 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 ));

Do you have any more efficient methods or the code above is incorrect.

Related Article

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.