Regexp and Prime numbers

This is a one-liner Ruby script that will tell you if a given number is
prime.

ruby -wle ‘puts “Prime” unless (“1” * ARGV[0].to_i) =~
/^1$|^(11+?)\1+$/’ [number]

I cannot take credit for this one – it originally came from Perl. The
website listed below gives the full explanation of how the regexp
works.

http://montreal.pm.org/tech/neil_kandalgaonkar.shtml

I highly recommend reading this if you want to flex your regexp muscles
today.

Blessings,
TwP

ruby -wle ‘puts “Prime” unless (“1” * ARGV[0].to_i) =~
/^1$|^(11+?)\1+$/’ 42

It may be the answer to life, the universe, and everything, but it
certainly isn’t prime!

On Mar 19, 2007, at 2:07 PM, Tim P. wrote:

http://montreal.pm.org/tech/neil_kandalgaonkar.shtml

I highly recommend reading this if you want to flex your regexp
muscles today.

Wow, that was just awesome.

James Edward G. II

Cool! I couldn’t resist porting it to Java, so here is my Java version
(It is not one-liner, but maybe one statement?) :

public class PrimeTester {
public static void main(String[] args) {
System.out.println(String.format(“%0” + args[0] + “d”,
0).matches(“^0$|^(00+?)\1+$”) ? “Not prime” : “Prime”);
}
}

http://davidtran.doublegifts.com/blog/?p=12

On 3/20/07, Tim P. [email protected] wrote:

It highlites some of the performance issues of backtracking in ruby1.8
sys 0m0.024s
But… on larger numbers…

Now that is very interesting. Do you know if Ruby 1.9 is running
Onigurma <sp?>, the new regexp handler?

For those of us on Windows command line:

ruby -wle “puts ‘Prime’ unless (‘1’ * ARGV[0].to_i) =~
/^1$|^(11+?)\1+$/”

That’s cool.

Jason

On 3/20/07, gga [email protected] wrote:

perl -wle ‘print “Prime” if (1 x shift) !~ /^1$|^(11+?)\1+$/’ 104729
Segmentation fault

perl -v
This is perl, v5.8.8 built for x86_64-linux-gnu-thread-multi

Now that is very interesting. Do you know if Ruby 1.9 is running
Onigurma <sp?>, the new regexp handler?