You're replying to a comment by Daniel.

Daniel Permalink
November 03, 2009, 20:38

Hi Peter,

The prime number one liner with the regexp is very interesting and surprisingly short.

I'm not a perl programmer, but at first glance I thought the regexp solution would be very slow (because the "base 1" representation would take a lot of space) and I thought I could write something slightly longer, but faster.

So, I came up with this thing:

perl -MList::Util=max -lne 'foreach (max(2,max(keys %p)+1)..$_) {$i=$_;scalar(grep(($i % $_) == 0, keys %p)) == 0 and $p{$i}=1}; $p{$_} and print "$_ is prime"'

which is more like two full lines on my terminal, but uses a set of already found primes (%p) and only does computations if the input line contains a number larger than all previous (so it should be better, right?..).

Well, guess what -- when testing with larger numbers, your regexp returned results instantly while my code needed 5 seconds for 10000 and about half a minute for 20000!..

So, maybe in Perl shorter does mean faster, too.

Reply To This Comment

(why do I need your e-mail?)

(Your twitter handle, if you have one.)

Type the word "unix_165": (just to make sure you're a human)

Please preview the comment before submitting to make sure it's OK.