A regular expression to check for prime numbers
noulakaz.net
noulakaz.net
No regular expression can check for prime numbers because the language { 1^n | n is prime } is not regular. You can see this by applying the pumping lemma: http://en.wikipedia.org/wiki/Pumping_lemma_for_regular_langu...
It was really confusing to me how this would work correctly on 12, 13, etc. until I read through there and realized that the program rewrote the number in unary (i.e. 2 -> 11, 3 -> 111, 4 -> 1111, etc.) before applying that regular expression.
From there, it does a quick test to correctly handle the zero and 1 case (empty string or a single 1), then it goes into the backtracking pattern, which tries to divide it by each number less than it until the parser succeeds or gives up. Anything matching is composite, anything not matching is prime.
Incidentally, whatever site he originally linked it from appears to be dead now.
An interesting pattern that wasn't immediately obvious, but a very inefficient way to detect primes :)
If your browser has Java applet support, here you can watch the regex succeed (demonstrating a number is composite) or fail (prime):
49: http://regex.powertoy.org/?pat=/^1%3F%24|^%2811+%3F%29\1+%24...
47: http://regex.powertoy.org/?pat=/^1%3F%24|^%2811+%3F%29\1+%24...
My favourite:
for calculations with big numbers, try F#
Yet scary how many folks confuse odd numbers with primes on the original blog's comments.