aboutsummaryrefslogtreecommitdiff
path: root/challenge-125
diff options
context:
space:
mode:
authorMohammad S Anwar <mohammad.anwar@yahoo.com>2021-08-15 19:31:30 +0100
committerMohammad S Anwar <mohammad.anwar@yahoo.com>2021-08-15 19:31:30 +0100
commit77fce3c8870cb065511df5db166f0b4d4845b26c (patch)
treed753fffada6a5a483ab250ba32e265e0b7c0b827 /challenge-125
parent985f74eb57705f4af35a7ca86c0e7a7e26b2e878 (diff)
downloadperlweeklychallenge-club-77fce3c8870cb065511df5db166f0b4d4845b26c.tar.gz
perlweeklychallenge-club-77fce3c8870cb065511df5db166f0b4d4845b26c.tar.bz2
perlweeklychallenge-club-77fce3c8870cb065511df5db166f0b4d4845b26c.zip
- Added solution by Pete Houston.
Diffstat (limited to 'challenge-125')
-rw-r--r--challenge-125/pete-houston/perl/ch-1.pl62
1 files changed, 62 insertions, 0 deletions
diff --git a/challenge-125/pete-houston/perl/ch-1.pl b/challenge-125/pete-houston/perl/ch-1.pl
new file mode 100644
index 0000000000..4fd5517372
--- /dev/null
+++ b/challenge-125/pete-houston/perl/ch-1.pl
@@ -0,0 +1,62 @@
+#!/usr/bin/env perl
+#===============================================================================
+#
+# FILE: 12501.pl
+#
+# USAGE: ./12501.pl N
+#
+# DESCRIPTION: Given a positive integer, print all unique Pythagorean
+# triples in which it features, or just "-1" if there are none.
+#
+# REQUIREMENTS: Math::Prime::Util
+# AUTHOR: Pete Houston (pete), cpan@openstrike.co.uk
+# ORGANIZATION: Openstrike
+# VERSION: 1.0
+# CREATED: 09/08/21
+#===============================================================================
+
+use strict;
+use warnings;
+use Math::Prime::Util qw/is_square/;
+
+my $n = shift;
+my $n2 = $n * $n;
+
+# Avoid duplicates, so store them in a hash keyed on either of the other
+# members of the triple.
+my %triples;
+
+# n squared could be the sum of 2 squares or the difference of 2 squares
+
+# Sum. Count downwards from n.
+my $go = $n;
+while (--$go > 4) {
+ next if exists $triples{$go};
+ my $sqdiff = $n2 - $go * $go;
+ store_if_sq (\%triples, $sqdiff, $n, $go);
+}
+
+# Difference. Count upwards from n.
+$go = $n;
+my $oldgo2 = $n2;
+while (1) {
+ my $go2 = ++$go * $go;
+ last if $n2 < ($go2 - $oldgo2);
+ my $sqdiff = $go2 - $n2;
+ store_if_sq (\%triples, $sqdiff, $n, $go);
+ $oldgo2 = $go2;
+}
+
+unless (scalar keys %triples) {
+ print "-1\n";
+ exit;
+}
+
+print "(@$_)\n" for values %triples;
+
+sub store_if_sq {
+ my ($tri, $sqdiff, @rest) = @_;
+ return unless is_square ($sqdiff);
+ my $diff = sqrt $sqdiff;
+ $tri->{$diff} = [$diff, @rest];
+}