Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re^3: ulam's spiral too slow

by bart (Canon)
on Apr 16, 2007 at 10:47 UTC ( [id://610314]=note: print w/replies, xml ) Need Help??


in reply to Re^2: ulam's spiral too slow
in thread ulam's spiral too slow

Can you (or any fellow monk) please clarify the need for caching the prime numbers in this particular scenario?
I know why I would cache it.

You are familiar with the optimization for check primality by only testing with odd numbers, which has been pointed out several times already in this thread. You can optimize even more by only testing division with prime numbers. It's actually the same kind of optimization: apart from 2, all even numbers are not prime (hence, needn't be tested) because they're all divisible by 2.

This extra optimization can reduce the number of tests you need to do significantly, especially for large numbers. You are already calculating all lower prime numbers in sequence, anyway. So you've already done the footwork. All you still have to do is store the found values. And change the code so it makes use of that.

And liverpole's code doesn't make use of that. Tsk.

I currently don't have the time to build a full-fledged memoized version of is_prime (but I might come back to it later). Maybe somebody else may feel the inclination...? It's not easy, you need to keep track of upto what level you have already calculated all primes, and fall back to liverpole's code if you're above that level, possibly raising the level if the step is small enough, i.e. you just checked the next odd number.

And, uh, I suspect liverpole found himself in the same situation, and that he gave up on it, too. In that scenarion, the cache of the primes may just be a leftover.

Replies are listed 'Best First'.
Re^4: ulam's spiral too slow
by smahesh (Pilgrim) on Apr 17, 2007 at 03:30 UTC

    Excellent. Based on your clarification, one can indeed use the divisibility check on previous computed primes to determine if current $number is prime.

    You can learn non-Perl stuff on perlmonks too!! :-)

    Thanks, Mahesh

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://610314]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (4)
As of 2024-03-29 05:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found