in reply to How can I tell if a number is a power of 2?

What is the most efficient way to shift that 1 to the other end so I can compare the value to 1 instead of using this horrible regex. Or is there a quicker way?

I might try table lookup.

sub is_power_of_2 { my $n = shift; 1 == grep { $_ == $n } ( 1 2 4 8 ... ) }

Replies are listed 'Best First'.
Re: Re: How can I tell if a number is a power of 2?
by Cine (Friar) on Jan 29, 2002 at 00:25 UTC
    if n is a power of two, then n = 2^x => lg n = x*lg 2 => lg n/lg 2 = x => lg n = x thus lg n is the power of 2 of your number. But usually only log10 and + natural log is avail, but lg x = log x/ lg e.


    T I M T O W T D I

    Edit by tye to replace PRE to CODE around long line(s)