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.