SUPPORT THE SITE WITH A CLICK

Subscribe Rss:

SUPPORT THE SITE WITH A CLICK

Monday, March 28, 2011

Ruby Challenge : Prime Numbers - Part II

Last week i have written a post on prime numbers, later i found this blog using regular expression for checking prime number or not?

Regexp Code
def is_prime(n)
     ('1' * n) !~ /^1?$|^(11+?)\1+$/
end
To 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