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.