diff options
| author | Mohammad S Anwar <Mohammad.Anwar@yahoo.com> | 2019-09-01 08:13:03 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2019-09-01 08:13:03 +0100 |
| commit | bc8c17c8c2ac784b8a09208b22974d1b50336642 (patch) | |
| tree | d16dbd8aa8ce0e647e44c59e4f1a1e987a60ca47 | |
| parent | e200d09264f1c7218af9e22b007efd77da3e834e (diff) | |
| parent | 9b8fe59ef04c427645a83c94108af2506164b0f8 (diff) | |
| download | perlweeklychallenge-club-bc8c17c8c2ac784b8a09208b22974d1b50336642.tar.gz perlweeklychallenge-club-bc8c17c8c2ac784b8a09208b22974d1b50336642.tar.bz2 perlweeklychallenge-club-bc8c17c8c2ac784b8a09208b22974d1b50336642.zip | |
Merge pull request #581 from jmaslak/joelle-23-2-1
Joelle's solutions to 23.2 in P6 & P5
| -rwxr-xr-x | challenge-023/joelle-maslak/perl5/ch-2.pl | 36 | ||||
| -rwxr-xr-x | challenge-023/joelle-maslak/perl6/ch-2.p6 | 25 |
2 files changed, 61 insertions, 0 deletions
diff --git a/challenge-023/joelle-maslak/perl5/ch-2.pl b/challenge-023/joelle-maslak/perl5/ch-2.pl new file mode 100755 index 0000000000..64a3bc5ffa --- /dev/null +++ b/challenge-023/joelle-maslak/perl5/ch-2.pl @@ -0,0 +1,36 @@ +#!/usr/bin/env perl +use v5.26; +use strict; +use warnings; + +# Turn on method signatures +use feature 'signatures'; +no warnings 'experimental::signatures'; + +use List::Util qw(first); +use Memoize; + +die("Please provide only number to decompose") unless @ARGV == 1; +my $num = shift @ARGV; +die("Number must be an integer") if "$num" ne int($num); + +say "$num = " . join( " * ", sort { $a <=> $b } prime_factors($num) ); + +sub prime_factors($i) { + if ( $i <= 1 ) { return @{ [$i] }; } + + my $first = first_factor($i); + return @{ [$i] } unless defined $first; # It is prime + return $first, prime_factors( $i / $first ); +} + +memoize('first_factor'); + +sub first_factor($i) { + if ( $i <= 0 ) { return } + + my $sqrt = int( sqrt($i) ); + + return first { ( $i % $_ ) == 0 } 2 .. $sqrt; +} + diff --git a/challenge-023/joelle-maslak/perl6/ch-2.p6 b/challenge-023/joelle-maslak/perl6/ch-2.p6 new file mode 100755 index 0000000000..3eee299be6 --- /dev/null +++ b/challenge-023/joelle-maslak/perl6/ch-2.p6 @@ -0,0 +1,25 @@ +#!/usr/bin/env perl6 +use v6; + +sub MAIN(UInt:D $num) { + # Yes, quotes in interpolation in quotes works in Perl6! + say "$num = {prime-factors($num).sort.join(" × ")}"; +} + +# Perl 6 makes beautiful recursion. :) + +multi sub prime-factors(0) { return @(0) } +multi sub prime-factors(1) { return @(1) } +multi sub prime-factors(UInt:D() $i where *.is-prime) { return @($i) } +multi sub prime-factors(UInt:D() $i) { + return @($i) if $i.is-prime; + + my $sqrt = sqrt($i).Int; + my $first = (2..$sqrt).first( $i %% * ); + + my @others = prime-factors($i / $first); + @others.push($first); + + return @others; +} + |
