|laziness, impatience, and hubris|
(Golf): Sieve of Eratosthenesby tilly (Archbishop)
|on May 19, 2001 at 11:03 UTC||Need Help??|
I got the idea for this from Re: RE: sieve of Eratosthenes.
Here is the challenge.
Write a function p that takes one argument $n, and returns an array of all of the primes up to and including $n.
Now there is a very short answer to this problem using the infamous RE from Abigail, namely:
Therefore I will add that the function must be clearly based on the Sieve of Eratosthenes. The sieve algorithm goes, "Form a list of integers. Knock out the evens other than 2. Knock out the multiples of 3. Knock out the multiples of 5. etc through the primes." For the purposes of this golf I will allow the following relaxations of the algorithm:
To sweeten the bait, sometime later tomorrow I will post my best solution. If anyone had come without 5 strokes of that answer, the best entry gets a free PerlMonks t-shirt. (The unlikely event of a tie will be resolved by whoever got there first.) Entries that I can find a failing boundary case for will not count.
For bonus marks, and a second possible t-shirt, the same problem but without the relaxation on the sieve. That is in the elimination round you must only mark off multiples of primes, and you cannot have sufficient wasted operations to change the Big-O of the algorithm. (ie You can waste a constant factor of overhead. But you cannot, for instance, spend most of your running time marking off array elements that are out of bounds.) However I will let you assume that $n is above a fixed number. (I am not sure how people will tackle this, but sometimes it is convenient to make a special case out of 2.)
A final note. Most mathematicians say that the first prime is 2. However those who produce lists of primes like to say 1. I don't care whether your sequence starts with 2 or 1, either is acceptable.
And an honorable mention goes to Arguile. OK, so he forgot to test whether pop populates $_ (it doesn't) but if that is what he can do after 6 weeks of Perl, I can only wonder what he will be like with a few more months under his belt...