I need to test primality on intervals between numbers which are really big (in the range of long long), so i need some fast algorithm for checking if a number is prime or not. Please suggest your ideas.
I came up with a really good algorithm, that is much faster than checking all the divisors - which of course also lets me crack public key encryption.
Hang on - I just need to close the window, there are all these black helicopters overhead ........
(Or look at http://stackoverflow.com/questions/627463/how-can-i-test-for-primality)
One good method is the Miller-Rabin test. It should be noted however, that this is only a probabilistic test.
Fastest would probably be to look it up in a precomputed list of primes. See here for example, they have up to 2^43112609-1 (largest known prime).
I believe that the asymptotically fastest current (non-probabilistic) primality test is the "Lenstra/Pomerance improved AKS", which has complexity that is essentially O(n^6).
However, the range of long long
(assuming a typical system where that is a 64 bit integer) is not really that big. In particular, there are only ~200 million primes less than 2^32, so using a fast probabilistic test, followed by trial division with a precomputed list of primes (or just looking the number up in a list of primes, if you have one) would be pretty darn fast in that range, and is probably the right way to go about it.
I would suggest the GNU MP library that uses the Miller-Rabin algorithm. I have used it for a few months and it's very fast.
Specifically, the function mpz_probab_prime_p does this, you can also use another function mpz_nextprime to find the next prime number greater than a number. I can post code samples if you would like.
Cobbal and grokus are right. The Miller-Rabin test is the most useful of the available algorithms. Yes, it is probabilistic, but really shouldn't scare you off. The test is the most widely used for practical purposes.
Note that the probability of false positives (there are no false negatives) can be made arbitrarily small by repeating the test.
Take a look at my answer here:
how to test a prime number 1000 digits long?
The test is very fast. If you are working in the 64-bit or smaller range, you can throw in a GCD with 30030 to save a bit of time for the majority of numbers.
If you want to test a long long for primality then the Baillie PSW primality test is a good choice. This test does one strong pseudoprime test and one Lucas test and hence is very fast. It is expected that there exist some composites that pass this test, but so far none are known, and there certainly is no exception below 1015. A variant of this test is for example used in Mathematica.