From 0fe435254749250667c2f38566f12f617e270cab Mon Sep 17 00:00:00 2001 From: Myoungjin JEON Date: Mon, 28 Sep 2020 00:03:43 +1000 Subject: [ch-079/jeongoon] add ch-1.hs, just little bit more better ch-1.pl, ch-1.raku --- challenge-079/jeongoon/perl/ch-1.pl | 35 ++++++++++++++++++++--------------- 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 ) { -- cgit