## Finding prime numbers using ~~voodoo~~ regular expressions

If you have learned how to program then the odds are that you have written a program that displays a list of prime numbers. A prime number generator is a programming rite of passage that is almost up there with the ubiquitous ‘Hello World‘ application (for programmers who are going on to do numerical work at least).

There are various ways you might choose to do it but I bet that your first (or even your second or third) thought wouldn’t be ‘*I know – I’ll use a regular expression‘.* Someone known only as ‘Abigail’ obviously thought that the world desperately needed such a regex since he / she came up with the following incantation

^1?$|^(11+?)\1+$

Which is a regular expression that I assure you can be used to generate a list of all the prime numbers. If you are in the mood for a puzzle then sit back, grab a cup of coffee and try to work out HOW it can generate the primes.

If you give up then head over to Python Programming for a full explanation along with Python code that demonstrates that it really does work.

Can anyone come up with regular expressions for other interesting series of numbers?

**Update (27th August 2009): **Someone pointed me to an alternative explanation here.

The code looks like pure white noise to me…how can people program in that language :-|

Just so you know, Abigail is definitely a “she”. I’ve met her at a conference.

But she’s just Abigail. Like Twiggy.

To be precise, that regex matches composite numbers, so the primes are the set of strings of 1s minus the language generated by the regex.

And I’m not sure what circumstances would lead to Abigail being a ‘he’ either.

“And I’m not sure what circumstances would lead to Abigail being a ‘he’ either.”

If it was a surname.