开发者

How does the regex expression that checks for prime numbers work? [duplicate]

开发者 https://www.devze.com 2023-03-01 09:48 出处:网络
This question already has answers here: How does this regular expression work? (2 answers) Closed 7 years ago.
This question already has answers here: How does this regular expression work? (2 answers) Closed 7 years ago.

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/
0

精彩评论

暂无评论...
验证码 换一张
取 消