in reply to How can I tell if a number is a power of 2?
cLive ;-)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 }
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 |