diff options
| author | Lubos Kolouch <lubos@kolouch.net> | 2022-02-26 11:19:24 +0100 |
|---|---|---|
| committer | Lubos Kolouch <lubos@kolouch.net> | 2022-02-26 11:19:24 +0100 |
| commit | 3044a2200c0fb28897de7879e3a7dc05dbeec56c (patch) | |
| tree | 592ac3a2d47782a26653b9982e73e8269cc2188f | |
| parent | c4e3b2a7e8db74784a52e62402ef90d0e7e9f0a8 (diff) | |
| download | perlweeklychallenge-club-3044a2200c0fb28897de7879e3a7dc05dbeec56c.tar.gz perlweeklychallenge-club-3044a2200c0fb28897de7879e3a7dc05dbeec56c.tar.bz2 perlweeklychallenge-club-3044a2200c0fb28897de7879e3a7dc05dbeec56c.zip | |
feat(challenge-153/lubos-kolouch/perl/ch-1.pl): Perl solution for Challenge 153 Task 1 LK
| -rw-r--r-- | challenge-153/lubos-kolouch/perl/ch-1.pl | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/challenge-153/lubos-kolouch/perl/ch-1.pl b/challenge-153/lubos-kolouch/perl/ch-1.pl new file mode 100644 index 0000000000..eec490830a --- /dev/null +++ b/challenge-153/lubos-kolouch/perl/ch-1.pl @@ -0,0 +1,46 @@ +use strict; +use warnings; + +# keep seen factorials in a cache to speed things up +my %fact_cache = (0 => 1); +my %left_fact_cache; + +sub calculate_factorial { + my $what = shift; + + return $fact_cache{$what} if $fact_cache{$what}; + + # let's utilize the fact that we are processing the numbers in sequence + $fact_cache{$what} = $what * $fact_cache{$what-1}; + + return $fact_cache{$what}; +} + +sub calculate_left_fact { + my $what = shift; + + return $left_fact_cache{$what} if $left_fact_cache{$what}; + + # let's utilize the fact that we are processing the numbers in sequence + $left_fact_cache{$what} = calculate_factorial($what-1) + $left_fact_cache{$what-1}; + + return $left_fact_cache{$what}; +} + + +sub get_left_factorials { + my $what = shift; + + my @output; + + for (1..$what) { + push @output, calculate_left_fact($_); + } + + return \@output; +} + +use Test::More; + +is_deeply(get_left_factorials(10), [1, 2, 4, 10, 34, 154, 874, 5914, 46234, 409114]); +done_testing; |
