-2

We know that all prime numbers are of the form 6k+-1. To check if n is a prime number, can't we just divide n by 6, take the floor of that, then check if adding or subtracting 1 equals n? That would check if a number is prime in constant time, right? If this is true, why do other methods bother using sieves for primality tests? Also, using this method, wouldn't finding a range of primes from 2 to n be O(n)? So this method is faster than the sieve of Eratosthenes?

Linus Kleen
  • 33,871
  • 11
  • 91
  • 99

3 Answers3

4

Yes, all primes are of the form 6k +/- 1, but that doesn't mean that each number that is of the form 6k +/- 1 is prime. Consider 25, which is 6 * 4 + 1. Clearly, 25 is not prime.

thedayturns
  • 9,723
  • 5
  • 33
  • 41
1

We know that all prime numbers are of the form 6k+-1.

But not all numbers in the form 6k+-1 are prime. (E.g. 6 * 4 + 1 = 25)

This means that your isPrime based on this test will give false positives (e.g. for 25). It will never give false negatives though, so it can be used to weed out some possibilities before you apply a real primality test.

You may find https://en.wikipedia.org/wiki/Primality_test#Simple_methods educational. In particular, the 6k+1 pattern is just one of many patterns that can be used in creating a naive primality test, the more general/optimized case of which ends up reducing to ... the Sieve of Eratosthenes.

Domenic
  • 110,262
  • 41
  • 219
  • 271
1

This works, but the utility is minor. Essentially, this statement is equivalent to "If a number is not divisible by 2 or 3, it might be prime."

6k is divisible by 6 (redundant check - same as divisible by 2 or 3).
6k + 1 may be prime
6k + 2 = 2(k+3) is divisible by 2
6k + 3 = 3(k+2) is divisible by 3
6k + 4 = 2(3k + 2) is divisible by 2 (redundant check)
6k + 5 may be prime. (and is equivalent to 6m - 1 for m = k+1)

So what we've actually accomplished is replaced trial division by 2, 3, (and eliminate multiples, sieve wise) with two slightly more complex operations. This means that this method is the first two iterations of the sieve of Eratosthenes.

So any algorithm using this property is equivalent to the following code:

boolean isPrime(n)
{
    if (n % 2 == 0) return false;
    if (n % 3 == 0) return false;
    return isPrimeRigourousCheck(n);
}

Which is pretty basic, and much simpler than solving the other equation 2 times.

Of interest, we can construct other similar rules. For example, the obvious next choice is

30k +- (1,7,11,13) but that gives us 8 cases to solve, and is equivalent to adding the single trial division:

if (n % 5 == 0) return false;  

to the code above. (which is a 3 iteration sieve)

Chris Cudmore
  • 29,793
  • 12
  • 57
  • 94