in reply to Primes. Again.

You start by taking the int of the square root of the number you want to test for prime. This is the largest number that could potentially divide cleanly into your number without a smaller number also dividing cleanly. Then you check all the primes currently stored, up to that max, to see if they divide into your number cleanly. If they do, you return 0 - no further processing is necessary. If you reach a prime larger than max, you return 1 - the number is a prime.

But what if there aren't enough primes in your array to check all the way up to max? You need to calculate those primes so you can check them. For all numbers from the current max stored prime + 1 to the square root of the potential prime, you check each number to see if it's a prime - using the same function! You add these primes to the stored primes array, and also check each one to see if it divides cleanly into your number. If it does divide cleanly, no further calculations are necessary, and the function returns 0.

Bottom line, only necessary calculations are made (as far as I can tell), minus a few minor tweaks such as skipping even numbers.

Replies are listed 'Best First'.
Re^2: Primes. Again.
by johngg (Canon) on Apr 27, 2006 at 19:01 UTC
    Sorry for the slow reply, today was full of meetings.

    I already had the first paragraph of your explanation as it is the same in essence as my solution, except that mine spends a lot of time filling out the sieve for each prime it finds. What I couldn't see to start with was why your solution was so quick. I was thinking "how can it fill in all the primes up to 36544645654 in that time?" However, as you point out, and I had managed to work out, you are only filling in the primes up to the square root of 36544645654 (191000 or so).

    No wonder it is so much faster. Very nice.

    Cheers,

    JohnGG