[Math] Understanding isPrime function from Wikipedia, a function that determines if a number is prime

algorithmsprime numbers

I know there are several questions on how to determine if a number is prime but none of them help me understand this particular implementation on Wikipedia, https://en.wikipedia.org/wiki/Primality_test
I understand the two if statements, not the for loop. Specifically, why does it increment i by 6 and why does it check to see if n % (i+2) equals zero? Here is the JavaScript implementation. Explain to me like I'm five please. Thanks in advance.

function isPrime(n) {
    if (n <= 3) { return n > 1; }
    if (n % 2 == 0 || n % 3 == 0) { return false; }
    for (var  i = 5; i * i <= n; i += 6) {
        if (n % i == 0 || n % (i + 2) == 0) { return false; }
    }
    return true;
}

Best Answer

This checks to see if $n$ is a multiple of 2 or 3 (at the start) and then (main loop) whether $n$ is a multiple of 5,7,11,13,17,19,23,25,29,31 etc. $i$ is going up by 6 starting at 5, and it checks $i$ and $i+2$. So the only question is why every single prime is in that list? It's because every prime bigger than 3 must leave remainder 1 or 5 when you divide it by 6. So done.

Related Question