diff options
| author | Mohammad S Anwar <Mohammad.Anwar@yahoo.com> | 2022-02-21 19:42:01 +0000 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-02-21 19:42:01 +0000 |
| commit | 9f41bf4d921fb1e1dd7edfcbe236f40f077ccb38 (patch) | |
| tree | 931610a9588956039d784724e44629c56bac5ce8 | |
| parent | 1b8a29378851e05454c2a4122a54cf3d36908899 (diff) | |
| parent | ab18a68915acaac839812de58817ebe3fc56a844 (diff) | |
| download | perlweeklychallenge-club-9f41bf4d921fb1e1dd7edfcbe236f40f077ccb38.tar.gz perlweeklychallenge-club-9f41bf4d921fb1e1dd7edfcbe236f40f077ccb38.tar.bz2 perlweeklychallenge-club-9f41bf4d921fb1e1dd7edfcbe236f40f077ccb38.zip | |
Merge pull request #5693 from choroba/ech153
Add solutions to 153: Left Factorials & Factorions by E. Choroba
| -rwxr-xr-x | challenge-153/e-choroba/perl/ch-1.pl | 56 | ||||
| -rwxr-xr-x | challenge-153/e-choroba/perl/ch-2.pl | 22 |
2 files changed, 78 insertions, 0 deletions
diff --git a/challenge-153/e-choroba/perl/ch-1.pl b/challenge-153/e-choroba/perl/ch-1.pl new file mode 100755 index 0000000000..a3797d8fd2 --- /dev/null +++ b/challenge-153/e-choroba/perl/ch-1.pl @@ -0,0 +1,56 @@ +#!/usr/bin/perl +use warnings; +use strict; + +use experimental 'signatures'; + +use List::Util qw{ sum product }; + +sub factorial ($n) { + product(1, 1 .. $n) +} + +sub left_factorial ($n) { + sum(map factorial($_), 0 .. $n - 1) +} + +{ my %F; + sub factorial_m ($n) { + $F{$n} //= product(1, 1 .. $n) + } +} + +{ my %LF = (1 => 1); + sub left_factorial_m ($n) { + $LF{$n} //= left_factorial_m($n - 1) + factorial_m($n - 1) + } +} + +use Test::More tests => 22; + +is left_factorial(1), 1; +is left_factorial(2), 2; +is left_factorial(3), 4; +is left_factorial(4), 10; +is left_factorial(5), 34; +is left_factorial(6), 154; +is left_factorial(7), 874; +is left_factorial(8), 5914; +is left_factorial(9), 46234; +is left_factorial(10), 409114; + +is left_factorial(20), 128425485935180314; + +is left_factorial_m($_), left_factorial($_) for 1 .. 10, 20; + +use Benchmark qw{ cmpthese }; +cmpthese(-3, { + plain => 'left_factorial(10)', + memoized => 'left_factorial_m(10)', +}); + +__END__ + + Rate plain memoized +plain 332153/s -- -96% +memoized 9473789/s 2752% -- diff --git a/challenge-153/e-choroba/perl/ch-2.pl b/challenge-153/e-choroba/perl/ch-2.pl new file mode 100755 index 0000000000..d091c506c1 --- /dev/null +++ b/challenge-153/e-choroba/perl/ch-2.pl @@ -0,0 +1,22 @@ +#!/usr/bin/perl +use warnings; +use strict; +use experimental 'signatures'; + +use List::Util qw{ sum }; + +{ my %factorial = (0 => 1); + $factorial{$_} = $factorial{ $_ - 1 } * $_ for 1 .. 10; + + sub is_factorion ($n) { + sum(@factorial{ split //, $n }) == $n + } +} + +use Test::More tests => 5; + +ok is_factorion(1); +ok is_factorion(2); +ok is_factorion(145); +ok is_factorion(40585); +ok ! is_factorion(125); |
