Clear questions and runnable code
get the best and fastest answer
Re^2: To Findout Prime numberby ZlR (Chaplain)
|on Jul 17, 2009 at 12:31 UTC||Need Help??|
perl -wle 'print "Prime" if (1 x shift) !~ /^1?$|^(11+?)\1+$/'
OK so I thought i'd elaborate a little on how this works since the monks from the chatterbox took time to explain it to me :)
So you have a number, say 6, and "write" it as a sequence of 1 ie (111111) .
ELISHEVA explains the math behind this :
It means that if you can write the number as M groups of K ones, then it factorizes as :
M * [ Sum(p=1->k) 1 ] which really is just M * K
Which means that our number can be divided by M (or K), and therefore it's not prime. Shmem gives an example: i.e. for m = 1763, the group found would be 11111111111111111111111111111111111111111 repeated 43 times - not prime
So how does the regexp implement that ? We can decompose it like this :
So the real trick is in (11+?). In a standalone context, it will only match 11. That's because +? means "once or more but the minimum number of times". On the other hand, ^(11+?)$ will match a whole sequence of ones from begining to end.
Here (11+?) is followed by \1+$ which means : itself, once or more, until the end of the line .
I understand that's what backtracking is. Eventually the regexp engine will try every grouping of ones and fine none.
The only problem is that for some numbers you get a Complex regular subexpression recursion limit (32766) exceeded error. My guess was that it happens when the engine has to try more than 32766 number of times, ie the first fail appears for a number that needs K>32766. That's not the case though, since prime number 32779 does not yield the error. 65558 does, though. I went on and brutforced it, to find that the error appears first with 65536, which is 2 * 32768, which computes since it needs two groups to match...