From 4017ec0ffb3b249c16468d19cee0ca295e15c138 Mon Sep 17 00:00:00 2001 From: Alexander Pankoff Date: Thu, 2 Dec 2021 18:26:46 +0100 Subject: Add solution for challenge-141 task 1 --- challenge-141/alexander-pankoff/perl/ch-1.pl | 63 ++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 challenge-141/alexander-pankoff/perl/ch-1.pl diff --git a/challenge-141/alexander-pankoff/perl/ch-1.pl b/challenge-141/alexander-pankoff/perl/ch-1.pl new file mode 100644 index 0000000000..bb4a1b6fb2 --- /dev/null +++ b/challenge-141/alexander-pankoff/perl/ch-1.pl @@ -0,0 +1,63 @@ +use strict; +use warnings; +use feature qw'say signatures'; +no warnings 'experimental::signatures'; + +use constant DEBUG => $ENV{DEBUG} // 0; + +run() unless caller(); + +sub run() { + say join( ' ', find_k_lowest_integers_with_exactly_n_divisors( 10, 8 ) ); +} + +sub find_k_lowest_integers_with_exactly_n_divisors ( $k, $n ) { + my @out; + + for ( my $i = 1 ; @out < $k ; $i++ ) { + my @divisors = find_divisors($i); + if ( @divisors == $n ) { + push @out, $i; + explain( $i, scalar @out, @divisors ) if DEBUG; + } + } + return @out; +} + +sub find_divisors($x) { + my @out; + for ( my $i = 1 ; $i <= int( $x / 2 ) ; $i++ ) { + push @out, $i if $x % $i == 0; + } + + push @out, $x; + + return @out; +} + +sub explain ( $x, $count, @divisors ) { + say "$x is the " + . to_ordinal($count) + . " such number having exactly " + . scalar @divisors + . " divisors."; + say join( ", ", @divisors ); + +} + +sub to_ordinal($x) { + my %map = ( + 1 => 'first', + 2 => 'second', + 3 => 'third', + 4 => 'fourth', + 5 => 'fifth', + 6 => 'sixth', + 7 => 'seventh', + 8 => 'eigth', + 9 => 'nineth', + 10 => 'tenth', + ); + + return $map{$x} // $x . 'th'; +} -- cgit