Possible Duplicate:
How to determine if a number is a prime with regex?
This page claims that this regular expression discovers non-prime numbers (and by counter-example: primes):
/^1?$|^(11+?)\1+$/
How does this find primes?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I think the article explains it rather well, but I’ll try my hand at it as well.
Input is in unary form. 1 is
1, 2 is11, 3 is111, etc. Zero is an empty string.The first part of the regex matches 0 and 1 as non-prime. The second is where the magic kicks in.
(11+?)starts by finding divisors. It starts by being defined as11, or 2.\1is a variable referring to that previously captured match, so\1+determines if the number is divisible by that divisor. (111111starts by assigning the variable to11, and then determines that the remaining1111is11repeated, so 6 is divisible by 2.)If the number is not divisible by two, the regex engine increments the divisor.
(11+?)becomes111, and we try again. If at any point the regex matches, the number has a divisor that yields no remainder, and so the number cannot be prime.