Short, elegant Regular expression for primality testing

by Craig Mayhew on Jan.22, 2012, under General

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

I was thoroughly impressed with this regex. I’m not going to reiterate what other people have already explained. So instead I will place links to other blogs that explain this very cool regex primality test.

http://montreal.pm.org/tech/neil_kandalgaonkar.shtml

http://www.noulakaz.net/weblog/2007/03/18/a-regular-expression-to-check-for-prime-numbers/

http://zmievski.org/2010/08/the-prime-that-wasnt

Thanks to <a href=”http://rantsofageek.com/”>Theo</a> for sending me a link to this!


Leave a Reply


In a bid to lower the spam levels on this blog, please type the following captcha code

Visit our friends!

A few highly recommended friends...