good chemistry is complicated, and a little bit messy LW 

PerlMonks 
Re^3: ulam's spiral too slowby bart (Canon) 
on Apr 16, 2007 at 10:47 UTC ( #610314=note: print w/ replies, xml )  Need Help?? 
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 fullfledged 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.
In Section
Seekers of Perl Wisdom

