3 ms·
Why does it have /^1?$/ ? Wouldn't that accept 0 and 1 as primes?
by ufo 3y ago
Why does it have /^1?$/ ? Wouldn't that accept 0 and 1 as primes?
- wongarsu 3y agoThe regular expression matches all non-primes (in base 1 encoding). 0 and 1 are not prime, so it matches them.
- rperce 3y agoI encourage you to re-read the article: you check that the number does not match the regex: > Is 7 prime? > > To know this, the function first generates “1111111” (from “1” \* 7) and tries to > see if that string does not match /^1?$|^(11+?)\1+$/. If there is no match, then > the number is prime. > > Notice that the regular expression has two parts (separated with the vertical bar |). > > The first part is /^1?$/ is trivial and matches with beginning of line (^), an > optional 1 (1?) and end of line ($) which implies that it matches either the > empty string or “1”. This simply indicates that calling that function with n==0 > or n==1 will correctly return false (as the “1” \* n will match with the first > part of the regular expression) I agree that the article formatting is a bit misleading.