A Perl Regular Expression That Matches Prime Numbers - good coders code, great reuse |
| A Perl Regular Expression That Matches Prime Numbers Posted: 26 Dec 2011 02:18 AM PST perl -lne '(1x$_) =~ /^1?$|^(11+?)\1+$/ || print "$_ is prime"' Can you figure out how it works? I give an explanation below, but try to figure it out yourself. Here is what happens when you run it: $ perl -lne '(1x$_) =~ /^1?$|^(11+?)\1+$/ || print "$_ is prime"' 1 2 2 is prime 3 3 is prime 4 5 5 is prime 6 7 7 is prime 8 9 10 11 11 is prime Here is how it works. First, the number is converted in its unary representation by Next, the unary string gets tested against the regular expression. If it matches, the number is a composite, otherwise it's a prime. The regular expression works this way. It consists of two parts The first part matches number The second part determines if two or more Let's look at the second regex part on numbers The number The number PS. I didn't invent this regular expression, it was invented in 1998 by Abigail. Don't take this regular expression too seriously, it's actually neither a regular expression (as defined in automata theory), nor a way to check if a number is a prime. It's just an awesome thing that Perl can do. Also if you wish to learn more about Perl one-liners, check out my Perl One-Liners Explained article series and download the perl1line.txt file. |
| You are subscribed to email updates from good coders code, great reuse To stop receiving these emails, you may unsubscribe now. | Email delivery powered by Google |
| Google Inc., 20 West Kinzie, Chicago IL USA 60610 | |
No comments:
Post a Comment
Keep a civil tongue.