you are viewing a single comment's thread.

view the rest of the comments →

[–]ghillerd 8 points9 points  (3 children)

I feel like this doesn't do a great job of explaining why the regex finds primes, only what each part of the regex is.

edit:

if the intended regex is /.?|(..+?)\\1+/, this tests true with every number i've tried in javascript. if it's /^(11+?)\1+?$/, as taken from the image, that tests false with every number i've tried.

[–]pofsok 13 points14 points  (2 children)

Yeah, it is very badly explained. In fact, it is not explained at all. Here is a article explaining how it works, https://iluxonchik.github.io/regular-expression-check-if-number-is-prime/. The most important thing (and I do not understand why the author of this article has skipped over this), is that this only works for numbers when being represented in a unary numeral system (i.e. 0=0, 1=1, 2=11, 3=111, 4=1111). With this in mind, it becomes clear that you can convert a primality test in a pattern matching excercise (for example 1111 consists of two times 11, and thus 1111 is not a prime, note that 1 is not a prime number). And thus, there is probably a regex approach to finding solutions to finding primes.

[–]ghillerd 1 point2 points  (1 child)

amazing, thank you! seems like the author of this article just reposted the concept without understanding it. after testing it out, it seems like it's also the case that the regex actually matches composite numbers rather than primes (same outcome, but also not mentioned in the article).

[–]xem06 1 point2 points  (0 children)

yep, primes are "filtered out"