How does this regex find primes? [duplicate]

杀马特。学长 韩版系。学妹 提交于 2019-11-28 02:59:08
Matchu

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 is 11, 3 is 111, 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 as 11, or 2. \1 is a variable referring to that previously captured match, so \1+ determines if the number is divisible by that divisor. (111111 starts by assigning the variable to 11, and then determines that the remaining 1111 is 11 repeated, so 6 is divisible by 2.)

If the number is not divisible by two, the regex engine increments the divisor. (11+?) becomes 111, 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.

Took me a minute to realize this is intended for numbers in base-1 (unary?)

Several people in this ycombinator discussion explain this quite well. Actually those explanations are more succinct than I think I can get, so I'll leave it to the link.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!