Prime Number Test by Regex

voice blog: prime_number_test_by_regex_2012-05-20.oga

the perl code is this:

perl -wle 'print "Prime" if (1 x shift) !~ /^1?$|^(11+?)\1+$/' ‹number›

How it works: given a number, say 7. Generate a string of 7 same chars, say "bbbbbbb". Then, use regex to test if repetition of 2 chars "bb" matches the string completely. If not, try 3 chars "bbb", then 4, etc.

The interesting thing is to put this into a single regex. The key regex is ^(bb+?)\1+$.

Popular posts from this blog

Browser User Agent Strings 2012

11 Years of Writing About Emacs

does md5 creates more randomness?