i see the code below from http://www.javascripter.net/faq/numberisprime.htm
leastFactor = function(n){
if (isNaN(n) || !isFinite(n)) return NaN;
if (n==0) return 0;
if (n%1 || n*n<2) return 1;
if (n%2==0) return 2;
if (n%3==0) return 3;
if (n%5==0) return 5;
var m = Math.sqrt(n);
for (var i=7;i<=m;i+=30) {
if (n%i==0) return i;
if (n%(i+4)==0) return i+4;
if (n%(i+6)==0) return i+6;
if (n%(i+10)==0) return i+10;
if (n%(i+12)==0) return i+12;
if (n%(i+16)==0) return i+16;
if (n%(i+22)==0) return i+22;
if (n%(i+24)==0) return i+24;
}
return n;
}
Does this mean that prime number always has same pattern every 30 after number 7?
Does this mean that from 7, when you add 30
the result of that number is prime, that number +4 is prime, that number +6 is always prime, and so on until +24, and there would be no more prime number between them?
No, but this code works because it is simply checking all values (sort of). You know that if a number is even, it is a multiple of 2 and not prime. Likewise, if it the rightmost digit is 5, you know that it is divisible by 5 and not prime. Using many rules like this, we can eliminate checking many different values that meet one of these parameters.
So, the script checks 2, sees that 2 is not a multiple of the input and knows that it never needs to check an even number again, so on and so forth.
The for loop is not generating only prime numbers. It could generate 187, which is not prime, but in practice, it never will because once the function checks 11, it will return.