diff options
| author | Joel Crosswhite <joel.crosswhite@ix.netcom.com> | 2020-12-01 17:45:32 -0700 |
|---|---|---|
| committer | Joel Crosswhite <joel.crosswhite@ix.netcom.com> | 2020-12-01 17:45:32 -0700 |
| commit | 9a709571310682177b5a30b6ac4fd2d517348a11 (patch) | |
| tree | 204d41c246c928e94716bbff136c6b3902472095 | |
| parent | aec23086dbb90f34ff085194d7d1082b659cee0a (diff) | |
| download | perlweeklychallenge-club-9a709571310682177b5a30b6ac4fd2d517348a11.tar.gz perlweeklychallenge-club-9a709571310682177b5a30b6ac4fd2d517348a11.tar.bz2 perlweeklychallenge-club-9a709571310682177b5a30b6ac4fd2d517348a11.zip | |
Added initial files for challenge 089.
Added README for first commit.
Created initial script for challenge 1 using binary GCD algorithm.
| -rw-r--r-- | challenge-089/jcrosswh/README | 1 | ||||
| -rw-r--r-- | challenge-089/jcrosswh/perl/ch-1.pl | 63 |
2 files changed, 64 insertions, 0 deletions
diff --git a/challenge-089/jcrosswh/README b/challenge-089/jcrosswh/README new file mode 100644 index 0000000000..144afd1a18 --- /dev/null +++ b/challenge-089/jcrosswh/README @@ -0,0 +1 @@ +Solution by Joel Crosswhite.
\ No newline at end of file diff --git a/challenge-089/jcrosswh/perl/ch-1.pl b/challenge-089/jcrosswh/perl/ch-1.pl new file mode 100644 index 0000000000..ff0f0979a0 --- /dev/null +++ b/challenge-089/jcrosswh/perl/ch-1.pl @@ -0,0 +1,63 @@ +#!/usr/bin/env perl + +use strict; +use warnings; + +=head1 NAME + +PWC 089 Challenge 1 + +=head1 SYNOPSIS + + $ ch-1.pl 3 + 3 + + $ ch-1.pl 4 + 7 + +=head1 DESCRIPTION + +Given a positive integer, this script will sum the +L<GCD|https://en.wikipedia.org/wiki/Greatest_common_divisor> of all possible +unique pairs between 1 and the inputed positive integer. + +=head1 AUTHORS + +Joel Crosswhite E<lt>joel.crosswhite@ix.netcom.comE<gt> + +=cut + +my $input = $ARGV[0]; +if (!defined($input) || $input !~ m/^[1-9]\d*$/) { + print "Usage: ch-1.pl <positive integer>\n"; + exit 1; +} + +my $retval = 0; +for (my $i = 1; $i < $input; $i++) { + for (my $k = $i + 1; $k <= $input; $k++) { + $retval += gcd($i, $k); + } +} + +print $retval . "\n"; +exit 0; + +sub gcd { + my ($first, $second, $d) = @_; + $d = 0 if !defined($d); + + if ($first == $second) { + return $first * 2 ** $d; + } elsif ($first % 2 == 0 && $second % 2 == 0) { + return gcd($first / 2, $second / 2, $d + 1); + } elsif ($first % 2 == 0) { + return gcd($first / 2, $second, $d); + } elsif ($second % 2 ==0) { + return gcd($first, $second / 2, $d); + } else { + my $c = abs($first - $second); + my $new_second = $first < $second ? $first : $second; + return gcd($c / 2, $new_second, $d); + } +}# gcd |
