Saturday, April 21, 2007

Primality Testing Using RegEx

Here are a couple of interesting methods for doing primality testing using RegEx in Perl and Python.

Method #1 (Perl):
perl -wle 'print "Prime" if (1 x shift) !~ /^1?$|^(11+?)\1+$/'

Method #2 (Perl):
perl -wle 'print "Prime" if (1 x shift) !~ /^1?$|^(11+?)\1+$/' [number]

Method #3 (Python):
import re
def is_prime(num):
return not re.match(r"^1?$|^(11+?)\1+$", "1" * num)

No comments: