From e30f5a2a410d7bf6e5d39d6ae13e5fdbac9943d4 Mon Sep 17 00:00:00 2001 From: Dave Jacoby Date: Tue, 5 Oct 2021 13:27:31 -0400 Subject: 133 --- challenge-133/dave-jacoby/blog.txt | 1 + challenge-133/dave-jacoby/perl/ch-1.pl | 27 +++++++++++++++++++ challenge-133/dave-jacoby/perl/ch-2.pl | 48 ++++++++++++++++++++++++++++++++++ 3 files changed, 76 insertions(+) create mode 100644 challenge-133/dave-jacoby/blog.txt create mode 100644 challenge-133/dave-jacoby/perl/ch-1.pl create mode 100644 challenge-133/dave-jacoby/perl/ch-2.pl diff --git a/challenge-133/dave-jacoby/blog.txt b/challenge-133/dave-jacoby/blog.txt new file mode 100644 index 0000000000..651f56428e --- /dev/null +++ b/challenge-133/dave-jacoby/blog.txt @@ -0,0 +1 @@ +https://jacoby.github.io/2021/10/05/mr-smith-squares-off-the-weekly-challenge-133.html \ No newline at end of file diff --git a/challenge-133/dave-jacoby/perl/ch-1.pl b/challenge-133/dave-jacoby/perl/ch-1.pl new file mode 100644 index 0000000000..84060a3f87 --- /dev/null +++ b/challenge-133/dave-jacoby/perl/ch-1.pl @@ -0,0 +1,27 @@ +#!/usr/bin/env perl + +use strict; +use warnings; +use feature qw{ say signatures state }; +no warnings qw{ experimental }; + +my @examples = ( 10, 27, 85, 101 ); + +for my $e (@examples) { + say join "\t", '', $e, isqrt1($e), isqrt2($e),; +} + +# the way we're requested to not use, for demonstration +sub isqrt1 ($n) { + return int sqrt $n; +} + +# another way: +sub isqrt2 ($n) { + my $j = 1; + while (1) { + return $j - 1 if $n < $j**2; + $j++; + } + return 1; +} diff --git a/challenge-133/dave-jacoby/perl/ch-2.pl b/challenge-133/dave-jacoby/perl/ch-2.pl new file mode 100644 index 0000000000..9b8be257f5 --- /dev/null +++ b/challenge-133/dave-jacoby/perl/ch-2.pl @@ -0,0 +1,48 @@ +#!/usr/bin/env perl + +use strict; +use warnings; +use feature qw{ say signatures state }; +no warnings qw{ experimental }; + +use List::Util qw{ sum sum0 }; +my @from_wikipedia = ( 4, 22, 27, 58, 85, 95, 121 ); +my %from = map { $_ => 1 } @from_wikipedia; + +my @smith_numbers = get_smith_numbers(); + +say join ', ', @smith_numbers; + +exit; + +sub sum_of_digits ( $n ) { return sum split //, $n } + +sub sum_of_factors ( $n ) { + my %factors; + my $output = 0; + my $nn = $n; + for my $i ( 2 .. $n - 1 ) { + if ( $nn % $i == 0 ) { + while ( $nn % $i == 0 ) { + $factors{$i}++; + $nn /= $i; + } + } + } + $output += sum0 map { sum( split //, $_ ) * $factors{$_} } keys %factors; + return $output || 0; +} + +sub get_smith_numbers { + my @output; + my $i = 2; + while ( scalar @output < 10 ) { + my $d = sum_of_digits($i); + my $f = sum_of_factors($i); + my $e = $d == $f ? 1 : 0; + push @output, $i if $e; + exit if $i > 500; + $i++; + } + return @output; +} -- cgit