Regexp Code
def is_prime(n) ('1' * n) !~ /^1?$|^(11+?)\1+$/ endTo know more, first this method generates "11111" as per the argument value n (Ex:n=5).
The first part is /^1?$ and matches with beginning ^ , an optional 1, 1? and then end of the string $, thus matches empty string or "1".If it matches then the number is not prime.
The second part is ^(11+?)\1+$, first matches with the beginning of the string^, then begin first stored group (, then matches with "1" followed by one or more ones minimally 1+? and end storing the first group ).Then \1+ match with the first group, repeated one or more times.Finally $ end of the string.
For more clear understanding, try to use the online rubular with reg exp.
No comments :
Post a Comment