Wednesday, October 24, 2018

Clever way of checking if number is prime

The solution relies on showing that p2 - 1 is a multiple of 2x2x2x3

First   
p2 - 1 = (p - 1) x (p + 1)

p must be odd, so p - 1 and p + 1 must be even. We have two of the factors we require.
Since p - 1 and p + 1 effectively form 2 consecutive even numbers one of them must be a multiple of 4, thus we have another of our factors of 2.
So far we have 2x2x2, now to get the factor of 3
p - 1, p & p + 1 form three consecutive numbers. In any three consecutive numbers one will be a multiple of 3, we know it is not p which is a multiple of 3, as this is prime, hence either p - 1 or p + 1 is a multiple. Therefore p2 - 1 has the factors 2, 2, 2 & 3 hence:
p2 - 1 = 24n
(Why must p be greater than 3? Well 3 is the only number which is both a multiple of 3 and prime)

* - I know 2 is prime, and even. But we are in the space greater than 3

bool isPrimeOrNot(int num) {

if (num < 0) return false;

if (num == 0 || num == 1) return false;

if (num == 2 || num == 3) return true;

if ((num * num - 1) % 24 == 0) return true;

return false;
}

Read more: http://www.java67.com/2014/01/how-to-check-if-given-number-is-prime.html#ixzz5UtLjP0dX

No comments:

Blog Archive