Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: How can I tell if a number is a power of 2?

by cLive ;-) (Prior)
on Jan 29, 2002 at 00:25 UTC ( [id://142180]=note: print w/replies, xml ) Need Help??


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

Obviously no mathematicians in the house :)
sub is_power_of_2 { return 0 unless $_[0]>0; # to avoid log error log($_[0])/log(2) - int(log($_[0])/log(2)) ? 0 : 1 }
cLive ;-)

Update: - Cine (not linked because of very irritating JS on home node) proves me wrong while I'm typing up :)

Update: - Damn you tye... This falls down as far as computing accuracy goes for 2 to the power of 29, 31, 39, 47 and probably a few more. Where's that posix math module when you need it :)

Ah well, here's another:

sub is_power_of_2 { local $_ = $_[0]; $_/=2 while ($_ > 1); return if ($_ - int($_)); 1; }

Replies are listed 'Best First'.
(tye)Re: How can I tell if a number is a power of 2?
by tye (Sage) on Jan 29, 2002 at 02:00 UTC

    Well, if you could portably ask whether the mantissa of the number was represented with all 0 bits (since the leading 1 bit is implied and so doesn't appear)...

    #!/usr/bin/perl -w use strict; my $mask; BEGIN { my $max= 2; $max *= 2 until 2*$max+1 == 2*$max; $mask= pack("d",$max) ^ pack("d",2*$max-1); } sub power2 { my( $n )= @_; return if ! $n; return( ( $mask & pack "d", $n ) !~ /[^\0]/ ); } for( split " ", do { local($/); <DATA> } ) { print "$_: ", power2($_)?1:0, "\n"; } __END__ 0 1 2 3 4 5 6 7 8 9 0.5 0.2 0.25 0.125 -1 -2 -3 -.25
    produces
    0: 0 1: 1 2: 1 3: 0 4: 1 5: 0 6: 0 7: 0 8: 1 9: 0 0.5: 1 0.2: 0 0.25: 1 0.125: 1 -1: 1 -2: 1 -3: 0 -.25: 1
    which has the advantage of catching negative-powers of 2 and negative powers-of-2. (:

            - tye (but my friends call me "Tye")

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2024-04-20 02:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found