diff options
| author | Myoungjin JEON <jeongoon@gmail.com> | 2020-09-28 00:03:43 +1000 |
|---|---|---|
| committer | Myoungjin JEON <jeongoon@gmail.com> | 2020-09-28 00:03:43 +1000 |
| commit | 0fe435254749250667c2f38566f12f617e270cab (patch) | |
| tree | a40aad6134925270241b22b97110f54b883e4edf | |
| parent | 563b5318ee80297fa540206e8a2a921c0096d67e (diff) | |
| download | perlweeklychallenge-club-0fe435254749250667c2f38566f12f617e270cab.tar.gz perlweeklychallenge-club-0fe435254749250667c2f38566f12f617e270cab.tar.bz2 perlweeklychallenge-club-0fe435254749250667c2f38566f12f617e270cab.zip | |
[ch-079/jeongoon] add ch-1.hs, just little bit more better ch-1.pl, ch-1.raku
| -rw-r--r-- | challenge-079/jeongoon/perl/ch-1.pl | 35 | ||||
| -rw-r--r-- | challenge-079/jeongoon/raku/ch-1.raku | 2 |
2 files changed, 21 insertions, 16 deletions
diff --git a/challenge-079/jeongoon/perl/ch-1.pl b/challenge-079/jeongoon/perl/ch-1.pl index 26043eefe3..9790cf08a2 100644 --- a/challenge-079/jeongoon/perl/ch-1.pl +++ b/challenge-079/jeongoon/perl/ch-1.pl @@ -16,23 +16,28 @@ BEGIN { $@ and usage(), exit 0; } -#sub sumSection ($) { # sum of the counts of bits between 2^(m) .. 2^(m+1)-1 -# state @K = (1, 3); -# my $m = shift; -# -# exists $K[$m] ? $K[$m] : ( $K[$m] = sum( 1<<$m, @K[0..$m-1] ) ); -#} - -#sub sumUptoPow2 ($) { # sum of bits between 0 .. 2^pow -# sum 1, # sumSection doesn't count the last bits of 2^pow -# map { sumSection $_ } 0 .. $_[0]-1 -#} - -# there is a simpler way to calculate, I realised today. -# but this is not significantly faster than before. +package older; +use List::Util qw(sum); + +sub sumSection ($) { # sum of the counts of bits between 2^(m) .. 2^(m+1)-1 + state @K = (1, 3); + my $m = shift; + + exists $K[$m] ? $K[$m] : ( $K[$m] = sum( 1<<$m, @K[0..$m-1] ) ); +} + +sub sumUptoPow2 ($) { # sum of bits between 0 .. 2^pow + sum 1, # sumSection doesn't count the last bits of 2^pow + map { sumSection $_ } 0 .. $_[0]-1 +} + +package main; + +# there is a simpler way to calculate, which I realised today. +# but this method is not significantly faster than previous one. sub sumUptoPow2 ($) { my $pow = shift; - 0.5 * $pow * (1 << $pow) + 1; + ( $pow * (1 << $pow) >> 1 ) + 1; # eqv. ($pow * (2**$pow) / 2 ) + 1; } sub countSetBits ($); diff --git a/challenge-079/jeongoon/raku/ch-1.raku b/challenge-079/jeongoon/raku/ch-1.raku index 9957f92016..196bfb2cc4 100644 --- a/challenge-079/jeongoon/raku/ch-1.raku +++ b/challenge-079/jeongoon/raku/ch-1.raku @@ -20,7 +20,7 @@ our &naive = {[+] (.base(2).indices(1).elems for ^$_[0]+1)}; # [+] 1, |(sum-a-section($_) for 0..($pow-1)); #} sub sum-upto-power2 ($pow) { # bits sum between 0 .. 2^pow - 1 + 0.5 * $pow * (1+<$pow); + 1 + ( $pow * (1+<$pow) ) +> 1 } sub count-set-bits ( UInt \N ) { |
