in reply to check for square-number with a regex
I have thought a bit more on this problem and was able to come up with a partial solution.
I would like to ask for some help in order to generalize it.
(It seems that I can't generalize it because I don't yet know well enough regexes in Perl)
MAIN IDEA: if n is a perfect square then n = p12kp22kp32k...pt2k(as you can see t is the number of prime divisors of n)
Now, for perfect squares whos prime divisors are only 2 and 3 then n=22k32k
CODE:
sub test { print $_[0] =~ $_[1] ? "matched\n" : "not matched\n"; } $p2 = qr/(1{4})*/; $p3 = qr/(1{9})*/; $issquare = qr/^(1{4})*(1{9})*$/; #for square numbers of form 2^2k * 3^2k test(('1'x36), $issquare);#2^2*3^2 <-- perfect square test(('1'x37), $issquare);#2^2*3^2+1 <-- not perfect square test(('1'x324), $issquare);#2^2*3^4 <-- perfect square test(('1'x325), $issquare);#2^2*3^4+1 <-- not perfect square test(('1'x9216), $issquare);#2^10*3^4 <-- perfect square test(('1'x9217), $issquare);#2^10*3^4+1 <-- not perfect square
The last test takes quite a bit and from now I can tell this is not a very efficient way to test for perfect squares(but this was pretty obvious from the very start, using a regex to check arithmetical properties of a number is not a problem where efficiency is desired, or is it ?)
RATAZONG's prime regex
The OP has provided a regex to check if a number is composite /^(11+)\1+$/
and this is a nice regex that works. However, in order to get a regex to check for primes with this we need to negate the regex(I failed while trying to use zero-width look-ahead look-behind negative in order to negate this,so if anyone has any suggestions or ideas on how to negate this ?). But to continue to a final solution let's suppose such a regex for checking if a string of 1s is of prime length and let's denote it $prime.(PROBABLY) A GENERAL SOLUTION
A general solution to the problem could be something like this
/^( ((?<prime2>$prime)\k<prime2>)* )*$/I've used named backreferences because if I used the numbered there would be some confusions between the current captures and the ones withing the $prime regex.
Again, it's still unclear to me(or I don't remember) if + or * mean repeat the same sequence multiple times or repeat a sequence that matches the sub-expression multiple times(that's because I'm still a noob).
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: check for square-number with a regex
by JavaFan (Canon) on Oct 24, 2009 at 16:06 UTC | |
|
Re^2: check for square-number with a regex
by spx2 (Deacon) on Oct 25, 2009 at 15:38 UTC |