Find primes in regexp
Posted by Jonas Elfström Fri, 30 Mar 2007 05:33:00 GMT
puts 'Prime' unless ('1' * 43) =~ /^1$|^(11+?)\1+$/
Change 43 to whatever you like and you will get Prime as output if it's a prime number.
EDIT: As you can see in the comments Neil Kandalonkar explained how the regexp by Abigail works.
EDIT 2011-04-06: I happened to stumble upon what I believe is the first time Abigail showed this to the world. It's in a post in comp.lang.perl.misc back in 1997. I also found that at http://www.cpan.org/misc/japh there's a couple more
perl -wle 'print "Prime" if (0 x shift) !~ m 0^\0?$|^(\0\0+?)\1+$0' perl -wle 'print "Prime" if ("m" x shift) !~ m m^\m?$|^(\m\m+?)\1+$mm'