I found a nice piece of regex code that checks for a prime number. I think I understand it but i’m still a little confused. Here’s the code: /^1?$|^(11+?)\1+$/
Can someone explain (step by step) exactly what is happening both with the regex code and how it actually relates to knowing if a number is prime or not?
The basic premise is that this regular expression examines a ones representation of the number (e.g. 5 = 11111). By checking for the presence of ones (
1) in certain positions or groupings it can identify the number as prime.Additional References:
http://montreal.pm.org/tech/neil_kandalgaonkar.shtml