Welcome to the Monastery PerlMonks

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

by larryk (Friar)
 on Jan 28, 2002 at 22:31 UTC ( #142140=note: print w/replies, xml ) Need Help??

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

After a session in the CB:
```#!perl
use strict;
use warnings;

use Benchmark qw/cmpthese/;

sub one {
my \$number = shift;
sprintf('%b',\$number) =~ /^10*\$/ ? 1 : 0;
}

sub two {
my \$number = shift;
1 == reverse sprintf('%b',\$number) ? 1 : 0;
}

sub three {
my \$number = shift;
1 == substr(sprintf('%b',\$number),0,1) ? 1 : 0;
}

my %h = map { \$_ ** 2 => 1 } (0..63);

sub jeffa {
my \$number = shift;
exists \$h{\$number} ? 1 : 0;
}

sub tye {
my \$x = shift;
0 == ( \$x & (\$x-1) ) ? 1 : 0;
}

my %h2 = ();
@h2{map \$_**2,0..63}; # word of mouth: by tilly

sub tilly { # really just another impl. of jeffa's lookup
my \$number = shift;
exists \$h2{\$number} ? 1 : 0;
}

cmpthese( -5,
{
one => q!one(rand 1000000)!,
two => q!two(rand 1000000)!,
three => q!three(rand 1000000)!,
tye => q!tye(rand 1000000)!,
jeffa => q!jeffa(rand 1000000)!,
tilly => q!tilly(rand 1000000)!,
}
);

__END__
Benchmark: running jeffa, one, three, tilly, two, tye, each for at lea
+st 5 CPU seconds...
jeffa:  6 wallclock secs ( 5.01 usr +  0.00 sys =  5.01 CPU) @ 62
+422.92/s (n=312614)
one:  5 wallclock secs ( 5.14 usr +  0.00 sys =  5.14 CPU) @ 11
+9667.70/s (n=614733)
three:  5 wallclock secs ( 5.25 usr +  0.00 sys =  5.25 CPU) @ 90
+412.81/s (n=474396)
tilly:  6 wallclock secs ( 5.01 usr +  0.00 sys =  5.01 CPU) @ 63
+202.16/s (n=316390)
two:  6 wallclock secs ( 5.14 usr +  0.00 sys =  5.14 CPU) @ 11
+9035.80/s (n=611725)
tye:  6 wallclock secs ( 5.25 usr +  0.00 sys =  5.25 CPU) @ 21
+0491.04/s (n=1104657)
Rate jeffa tilly three   two   one   tye
jeffa  62423/s    --   -1%  -31%  -48%  -48%  -70%
tilly  63202/s    1%    --  -30%  -47%  -47%  -70%
three  90413/s   45%   43%    --  -24%  -24%  -57%
two   119036/s   91%   88%   32%    --   -1%  -43%
one   119668/s   92%   89%   32%    1%    --  -43%
tye   210491/s  237%  233%  133%   77%   76%    --

Create A New User
Node Status?
node history
Node Type: note [id://142140]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (6)
As of 2018-01-22 21:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
How did you see in the new year?

Results (237 votes). Check out past polls.

Notices?