regex - How does this weird JavaScript function for primality check work? -
this question has answer here:
- how determine if number prime regex? 4 answers
this function:
var isprime = function(x) { return (!(/^,?$|^(,,+?)\1+$/.test(array(++x)))); };
it works small numbers, when number large, throws exception saying invalid array length. cannot understand what's going on here. regex test do? why code work?
array(++x)
first produces string of x
commas.
the regex now:
^,?$ // match 1 , or none | // or ... ^(,,+?)\1+$ // specific number of commas, elaboration below:
the number of commas equal @ least 2 commas, repeat till end. it's attempting is:
it first attempts match 2 commas (
,+?
matches @ least 1,
lazily), , use match multiples of 2, except 2 because backreference of\1
compulsory. multiples of 2 because^(,,)\1+$
matches number of,
.sidenote:
\1
backreference , match first capture group matched, in initial case(,,)
. in first phase,\1
match 2 commas.if there's match, means there number of commas , number not prime.
if above didn't match, matches 3 commas, , use match multiples of 3, again, except 3 itself. multiples of 3 because
^(,,,)\1+$
matches numbers of,
in multiples of 3.sidenote: time,
\1
match(,,,)
since that's in capture group. in second phase,\1
match 3 commas.if there's match, means there number of commas divisible 3, , hence, not prime number.
and on. can see pattern?
so regex check numbers 2 until (,,+?)
equal in length array(++x)
returns. of course, big numbers, can different sorts of errors:
the number pass function large regex you'll "a stack overflow regex trying keep many things in memory it's trying find match" floris mentioned in comments (this occurs before next error on node.js);
the array formed
array(++x)
has many elements js doesn't support.
so if regex matches, it's not prime number. that's why have !
@ start negate result of regex test.
Comments
Post a Comment