diff options
| author | Abigail <abigail@abigail.be> | 2020-09-21 17:52:07 +0200 |
|---|---|---|
| committer | Abigail <abigail@abigail.be> | 2020-09-21 18:28:18 +0200 |
| commit | 1da0d24d7d9480bb239b1a5584d1f14460627f44 (patch) | |
| tree | abd5d1b7b0bb5692d8341d1a7cace2210581940c | |
| parent | dfdbb9d3c54c2f4da70d04186425a39f3193daa4 (diff) | |
| download | perlweeklychallenge-club-1da0d24d7d9480bb239b1a5584d1f14460627f44.tar.gz perlweeklychallenge-club-1da0d24d7d9480bb239b1a5584d1f14460627f44.tar.bz2 perlweeklychallenge-club-1da0d24d7d9480bb239b1a5584d1f14460627f44.zip | |
Perl solution for Week 79.
| -rw-r--r-- | challenge-079/abigail/perl/ch-1.pl | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/challenge-079/abigail/perl/ch-1.pl b/challenge-079/abigail/perl/ch-1.pl new file mode 100644 index 0000000000..a2a8d27818 --- /dev/null +++ b/challenge-079/abigail/perl/ch-1.pl @@ -0,0 +1,51 @@ +#!/opt/perl/bin/perl + +use 5.032; + +use strict; +use warnings; +no warnings 'syntax'; + +# +# Challenge: +# +# You are given a positive number $N. +# +# Write a script to count the total numbrer of set bits of the binary +# representations of all numbers from 1 to $N and return +# $total_count_set_bit % 1000000007. +# +# https://perlweeklychallenge.org/blog/perl-weekly-challenge-079/ +# + +# +# This is A000778 (https://oeis.org/A000788). There's a recursive formala +# for the number of bits in the binary representation of 0 .. $N: +# +# bits (0) = 0 +# bits (2 * N) = bits (N) + bits (N - 1) + N +# bits (2 * N + 1) = 2 * bits (N) + N + 1 +# + +use experimental 'signatures'; +use experimental 'lexical_subs'; + +use integer; + +my $BIG_NUM = 1_000_000_007; + +sub bits ($n) { + state $bits; + $$bits {$n} ||= + $n == 0 ? 0 + : do { + my $half = int ($n / 2); + bits ($half) + $half + ($n % 2 ? bits ($half) + 1 + : bits ($half - 1)) + } +} + +say bits (<>) % $BIG_NUM; + + +__END__ |
