aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorE. Choroba <choroba@matfyz.cz>2020-08-04 14:56:46 +0200
committerE. Choroba <choroba@matfyz.cz>2020-08-04 14:56:46 +0200
commit87b6e596991b8bebbf362cc53336c0535b465e78 (patch)
tree302c27240e035bd65b9624d2f93e2b990916956f
parent97131b3313551350f7c7a073d7ad401a1db9d23f (diff)
downloadperlweeklychallenge-club-87b6e596991b8bebbf362cc53336c0535b465e78.tar.gz
perlweeklychallenge-club-87b6e596991b8bebbf362cc53336c0535b465e78.tar.bz2
perlweeklychallenge-club-87b6e596991b8bebbf362cc53336c0535b465e78.zip
Solve 072 (Trailing Zeros and Lines Range) by E. Choroba
In 072/1, ignore the N <= 10 condition. We can solve it fast for much larger Ns, also, it's N == 25 where it starts to get tricky and interesting. In 072/2, specify the input filename as the last argument to make it optional. $. is needed in the range operator as only literal numbers are interpreted as line numbers directly.
-rwxr-xr-xchallenge-072/e-choroba/perl5/ch-1.pl47
-rwxr-xr-xchallenge-072/e-choroba/perl5/ch-2.pl9
2 files changed, 56 insertions, 0 deletions
diff --git a/challenge-072/e-choroba/perl5/ch-1.pl b/challenge-072/e-choroba/perl5/ch-1.pl
new file mode 100755
index 0000000000..fe99c47555
--- /dev/null
+++ b/challenge-072/e-choroba/perl5/ch-1.pl
@@ -0,0 +1,47 @@
+#!/usr/bin/perl
+use warnings;
+use strict;
+
+use Math::BigInt;
+
+sub factorial {
+ my ($n) = @_;
+ my $p = 'Math::BigInt'->new(1);
+ $p *= $_ for 1 .. $n;
+ $p
+}
+
+sub trailing0s {
+ my ($n) = @_;
+ length((factorial($n) =~ /(0*)$/)[0])
+}
+
+sub trailing0s_fast {
+ my ($n) = @_;
+ my $z = 0;
+ my $i = 1;
+ $z += int($n / ($i *= 5)) while $i < $n;
+ return $z
+}
+
+use Test::More;
+
+subtest factorial => sub {
+ is factorial(0), 1;
+ is factorial(1), 1;
+ is factorial(5), 120;
+};
+
+subtest trailing0s => sub {
+ for my $n (0 .. 1000) {
+ is trailing0s($n), trailing0s_fast($n), "fast $n";
+ }
+};
+
+done_testing();
+
+use Benchmark qw{ cmpthese };
+cmpthese(-3, {
+ slow => 'trailing0s(2000)',
+ fast => 'trailing0s_fast(2000)',
+});
diff --git a/challenge-072/e-choroba/perl5/ch-2.pl b/challenge-072/e-choroba/perl5/ch-2.pl
new file mode 100755
index 0000000000..fbefa6b8be
--- /dev/null
+++ b/challenge-072/e-choroba/perl5/ch-2.pl
@@ -0,0 +1,9 @@
+#!/usr/bin/perl
+use warnings;
+use strict;
+
+my ($from, $to) = (shift, shift);
+while (<>) {
+ print if ($. == $from) .. ($. == $to);
+}
+