Peter
Peter Campbell Smith

Triples and trees

Weekly challenge 125 — 9 August 2021

Week 125: 9 Aug 2021

Task 1

Task — Pythagorean triples

You are given a positive integer $n. Write a script to print all Pythagorean Triples containing $n as a member. Print -1 if it isn’t a member of any. Triples with the same set of elements are considered the same, i.e. if your script has already printed (3, 4, 5), then (4, 3, 5) should not be printed.

The famous Pythagorean theorem states that in a right-angled triangle, the length of the two shorter sides and the length of the longest side are related by $a ** 2 + $b ** 2 = $c ** 2.

$a, $b, $c is called a Pythagorean triple.

Examples


Example 1:
Input: $N = 5
Output:
	(3, 4, 5)
	(5, 12, 13)

Example 2:
Input: $N = 13
Output:
	(5, 12, 13)
	(13, 84, 85)

Example 3:
Input: $N = 1
Output:
	-1

Analysis

What is our field of candidates? Clearly both $a and $b are less than $c, and we can stipulate that $a is less than $b.

There may be solutions if either $c == $n or $a == $n.

To find $c == $n solutions we need to check values of $a up to int(sqrt($n ** 2 / 2)) looking for cases where
$n ** 2 - $a ** 2 is a perfect square - ie $b ** 2.

To find $a == $n solutions we need to check values of $b less than
2 * $b + 1 > $n ** 2 looking for cases where $n ** 2 + $b ** 2 is a perfect square - ie $c ** 2.

Try it 

Try running the script with any input:



example: 24

Script


#!/usr/bin/perl

# Peter Campbell Smith - 2021-08-08
# PWC 125 task 1

use strict;
use warnings;

my ($a, $b, $c, $n, $s, @solutions);

# input n
print qq[n: ];
$n = <>;
chomp($n);

# test for $c == $n
for $a (1 .. int(sqrt($n ** 2 / 2))) {
    $solutions[$s++] = qq[    ($a, $b, $n)\n] if $b = is_a_square($n**2 - $a**2);
}

# test for $a == $n
for $b (1 .. 2 ** 32) {
    last if 2 * $b + 1 > $n ** 2;
    $solutions[$s++] = qq[    ($n, $b, $c)\n] if $c = is_a_square($n**2 + $b**2);   
}

# solutions
print qq[\nInput: \$N = $n\nOutput:\n];
for $s (@solutions) { print $s };
print qq[-1\n] unless (scalar @solutions);

#---

sub is_a_square {
    my $test = sqrt($_[0]);
    return $test == int($test) ? $test : 0;
}

Output

n: 
Input: $N = 24
Output:
    (24, 7, 25)
    (24, 10, 26)
    (24, 18, 30)
    (24, 32, 40)
    (24, 45, 51)
    (24, 70, 74)
    (24, 143, 145)

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain