diff options
| author | Jörg Sommrey <28217714+jo-37@users.noreply.github.com> | 2020-09-25 19:56:20 +0200 |
|---|---|---|
| committer | Jörg Sommrey <28217714+jo-37@users.noreply.github.com> | 2020-09-25 19:57:36 +0200 |
| commit | cb9504ae9ba71814d82d020e0beff1bc1ddd6104 (patch) | |
| tree | c3b31beba3cefc1d98ecfe57339d1c9f715edcac | |
| parent | 9705f076c0958bf9479957cc9c8f2a4fbe0f7cf1 (diff) | |
| download | perlweeklychallenge-club-cb9504ae9ba71814d82d020e0beff1bc1ddd6104.tar.gz perlweeklychallenge-club-cb9504ae9ba71814d82d020e0beff1bc1ddd6104.tar.bz2 perlweeklychallenge-club-cb9504ae9ba71814d82d020e0beff1bc1ddd6104.zip | |
Found silver bullet
| -rwxr-xr-x | challenge-079/jo-37/perl/ch-1.pl | 14 |
1 files changed, 9 insertions, 5 deletions
diff --git a/challenge-079/jo-37/perl/ch-1.pl b/challenge-079/jo-37/perl/ch-1.pl index 67ec7adfa8..b2ac754190 100755 --- a/challenge-079/jo-37/perl/ch-1.pl +++ b/challenge-079/jo-37/perl/ch-1.pl @@ -3,8 +3,11 @@ use Test2::V0; no warnings 'recursion'; use bigint; +use Memoize; use constant MOD => 1000000007; +memoize 'bitsum'; + # Calculate the sum of 1-bits in all numbers from 0 to n. Going from 0 # to n instead of 1 to n does not change the result, but simplifies the # calculation. @@ -30,17 +33,18 @@ sub bitsum { # When splitting a full power-of-two part, both sub-parts to be # recursed into are the same. This leads to a shortcut for at least # half of the calculations. - $offset + ($allone == $offset - 1 ? 2 * bitsum($allone) : bitsum($allone) + bitsum($offset - 1)); + $offset + ($allone == $offset - 1 ? + 2 * bitsum($allone) : + bitsum($allone) + bitsum($offset - 1)); } -# Get the modulus. +# Apply the modulus. sub bitsum_mod { - return bitsum(shift) % MOD; + bitsum(shift) % MOD; } is bitsum_mod(4), 5, 'first example'; is bitsum_mod(3), 4, 'second example'; -ok +(bitsum(1e9) > MOD), 'large bitsum'; -ok +(bitsum_mod(1e9) < MOD), 'large bitsum with modulus'; +is bitsum_mod(77347884), 1, 'silver bullet'; done_testing; |
