Find primes in regexp

Posted by Jonas Elfström Fri, 30 Mar 2007 05:33:00 GMT

In an earlier post the example code did find prime numbers. Recently I stumbled over a really cool regexp hack that also deals with primes. This is how you execute that regexp in Ruby:

puts 'Prime' unless ('1' * 43) =~ /^1$|^(11+?)\1+$/

Change 43 to whatever you like and you will get Prime as output if it's a prime number. EDIT: As you can see in the comments Neil Kandalonkar explained how the regexp by Abigail works.

Posted in ,  | 3 comments

Comments

  1. Avatar Neil Kandalgaonkar said 57 days later:

    As the page makes clear, credit should go to Abigail. I merely explained it.

  2. Avatar Jonas Elfström said 58 days later:

    Sorry, now it has been corrected.

  3. Avatar Jonas Elfström said 905 days later:

    Seems Neils site has gone missing. Here’s another nice explanation: http://paddy3118.blogspot.com/2009/08/story-of-regexp-and-primes.html


Email will not be shown. Enter email to show Gravatar.

   Comment Markup Help Preview comment