Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: check for power of a number with regex

by ikegami (Patriarch)
on Oct 26, 2009 at 01:25 UTC ( [id://803188]=note: print w/replies, xml ) Need Help??


in reply to check for power of a number with regex

Well, this works:

my $n = ...; my $b = ...; my @possibles; my $p = '1'; while ($p <= $n) { push @possibles, ('1' x $p); $p *= $b; } my ($pat) = map qr/$_/, join '|', @possibles; print( "$n: ", ('1' x $n) =~ /^$pat\z/ ?1:0, "\n" );

You can do almost all of the above inside the pattern, except for the $n <= $number check:

my $n = ...; my $b = ...; my $b_m1 = $b-1; my $pat = qr/(1|((?-2))\g{-1}{$b_m1})/; print( "$n: ", ('1' x $n) =~ /^$pat\z/ ?1:0, "\n" );

Without that check, the regex engine preemptively (and sometimes accurately) throws "Infinite recursion in regex".

Back to the drawing board.

Update: As best as I can tell, you'd need to be able to change the topic as follows:

local our $pat; $pat = qr/ 1 | (1+) \g{-1}{$b_m1} (?(?{ $^N =~ $pat })(?=)|(?!)) /x;

But that deosn't even work *with* (?{})!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://803188]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (9)
As of 2024-03-28 11:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found