Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

To save a click, the regex in question is: ^1?$|^(11+?)\1+$ (it checks if a unary number is not prime.

It is kind of surprising to hear that regex can do that, but once you see the regex its kind of obvious. Its just checking if the number is 1, or if the number can be represented by 2 or more 1's repeated at least 2 times. Which is literally the definition of a prime (is the number divisible by a number >= 2)



I had a hunch that maybe a lookahead might help a bit, but it turned out to be slower:

  /^(..+?)(?=\1+$)/
Edit: of course, silly me, +? is non-greedy.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: