Tassos Bassoukos

Environmentaly friendly. Using 100% recycled electrons.

Smallest code segments?

Quick: how long is the shortest program to calculate the first prime number after a given number? The answer might surprise you!

In perl, it's about 60 characters:

perl -e '$i=$ARGV[0]+1;$i++while("."x$i)=~/^(..+?)\1+$/;print"$i\n";' 90

Of course, I believe APL will win that contest hands down...

P.S: There's even a perl competition to produce the shortest code for a given problem, with the name Perl Golf...

@ Thursday, 20 July 2006, 15:22 in (Self, Software) - 9 comments

One Laptop Per Child >> << Eclipse and PermGen space...

Comments
  1. Comment by Anonymouson Thursday, 20 July 2006, 16:29
    wtf
  2. Comment by jhnon Thursday, 20 July 2006, 16:29
    sorry, that was me.
  3. Comment by jhnon Thursday, 20 July 2006, 16:35
    $i=$ARGV[0]+1;
    $i++while("."x$i)=~/^(..+?)\1+$/;
    print"$i\n";

    I can undestand most of the program. I'm only a little confused about the second line, what is that trick with the dots?
  4. Comment by Tassos Bassoukos on Friday, 21 July 2006, 17:35
    The second line just finds the next $i that is a prime number. The ("." x $i) =~ /^(..+?)\1+$/ part is the test for primeness. ("." x $i) produces a string of length $i composed of dots. The regular expression /^(..+?)\1+$/ matches any string whose length is a multiple of two numbers larger than one, hence matching only when the length is not prime.

    Hope this helps.
  5. Comment by jhnon Saturday, 22 July 2006, 21:22
    The regular expression /^(..+?)\1+$/ matches any string whose length is a multiple of two numbers larger than one, hence matching only when the length is not prime.

    what is the value of \1 the first time?

  6. Comment by Tassos Bassoukos on Tuesday, 25 July 2006, 13:23
    Duh, \1 matches the contents of the first parenthesized group. Perhaps ("0" x $i) =~ /^(00+?)\1+$/ reads better?
  7. Comment by jhnon Tuesday, 25 July 2006, 14:00
    i knew that but i was confused until i understood how the ..+? part is checked again and again with all its' possible lengths. Actually the ? was that confused me, it made me think that \1 was always equal to '..' (the smallest match of /..+?/)
  8. Comment by Tassos Bassoukos on Tuesday, 25 July 2006, 15:07
    Ah no - perldoc perlre states that the \1 matches the matched characters of the referenced group, not the regular expression of the group (I hope that makes sense...). So, if the first match is "..." then \1+ means "..." one or more times. The '?' is the negative-greediness modifier.
  9. Comment by Anonymouson Tuesday, 25 July 2006, 17:23
    yes, which means that (..+?) of "........"'s first match is ".." and with (..+?)\1+ does not match, and _then_ it tries (..+?) = "..." and (..+?)\1+ matches.
Post a comment
Name:
Webpage:
Save this info.
Comment Text:
Trackback

The Trackback link for this post is here.