How does the regex expression that checks for prime numbers work? [duplicate]
I 开发者_如何转开发found a nice piece of regex code that checks for a prime number. I think I understand it but i'm still a little confused. Here's the code: /^1?$|^(11+?)\1+$/
Can someone explain (step by step) exactly what is happening both with the regex code and how it actually relates to knowing if a number is prime or not?
The basic premise is that this regular expression examines a ones representation of the number (e.g. 5 = 11111). By checking for the presence of ones (1
) in certain positions or groupings it can identify the number as prime.
Additional References:
- Credit where credit is due - http://montreal.pm.org/tech/neil_kandalgaonkar.shtml
- Great explanation - http://www.noulakaz.net/weblog/2007/03/18/a-regular-expression-to-check-for-prime-numbers/
精彩评论