View Subcategory
Find all Pythagorean triangles with length or height less than or equal to 20
Pythagorean triangles are right angle triangles whose sides comply with the following equation:
a * a + b * b = c * c
where c represents the length of the hypotenuse, and a and b represent the lengths of the other two sides. Find all such triangles where a, b and c are non-zero integers with a and b less than or equal to 20. Sort your results by the size of the hypotenuse. The expected answer is:
a * a + b * b = c * c
where c represents the length of the hypotenuse, and a and b represent the lengths of the other two sides. Find all such triangles where a, b and c are non-zero integers with a and b less than or equal to 20. Sort your results by the size of the hypotenuse. The expected answer is:
[3, 4, 5]
[6, 8, 10]
[5, 12, 13]
[9, 12, 15]
[8, 15, 17]
[12, 16, 20]
[15, 20, 25]
perl
#!/usr/bin/perl
my @results;
for my $x (1..20) {
for my $y ($x..20) {
my $z = sqrt($x**2+$y**2);
push @results, [$x,$y,$z] if $z == int($z);
}
}
for my $triangle ( sort { $a->[2] <=> $b->[2] } @results) {
print "[".join(',',@$triangle)."]\n";
}
my @results;
for my $x (1..20) {
for my $y ($x..20) {
my $z = sqrt($x**2+$y**2);
push @results, [$x,$y,$z] if $z == int($z);
}
}
for my $triangle ( sort { $a->[2] <=> $b->[2] } @results) {
print "[".join(',',@$triangle)."]\n";
}
java
SortedSet<List<Integer>> results = new TreeSet<List<Integer>>(new Comparator<List<Integer>>() {
public int compare(List<Integer> o1, List<Integer> o2) {
return o1.get(2).compareTo(o2.get(2));
}
});
for (int x = 1; x <= 20; x++) {
for (int y = 1; y <= 20; y++) {
double z = Math.hypot(x, y) ;
if ((int) z == z)
results.add(Arrays.asList( new Integer[] { x, y, (int) z }));
}
}
public int compare(List<Integer> o1, List<Integer> o2) {
return o1.get(2).compareTo(o2.get(2));
}
});
for (int x = 1; x <= 20; x++) {
for (int y = 1; y <= 20; y++) {
double z = Math.hypot(x, y) ;
if ((int) z == z)
results.add(Arrays.asList( new Integer[] { x, y, (int) z }));
}
}
cpp
vector<solution> solutions;
for (int a = 1; a <= 20; ++a)
for (int b = a + 1; b <= 20; ++b)
{
int c_squared = a*a + b*b;
int c = b + 1;
while (c * c < c_squared)
++c;
if (c * c == c_squared)
solutions.push_back(make_tuple(a, b, c));
}
sort(begin(solutions), end(solutions),
[](const solution& s1, const solution& s2) { return get<2>(s1) < get<2>(s2); });
for (const auto &s: solutions)
cout << '[' << get<0>(s) << ", " << get<1>(s) << ", " << get<2>(s) << ']' << endl;
for (int a = 1; a <= 20; ++a)
for (int b = a + 1; b <= 20; ++b)
{
int c_squared = a*a + b*b;
int c = b + 1;
while (c * c < c_squared)
++c;
if (c * c == c_squared)
solutions.push_back(make_tuple(a, b, c));
}
sort(begin(solutions), end(solutions),
[](const solution& s1, const solution& s2) { return get<2>(s1) < get<2>(s2); });
for (const auto &s: solutions)
cout << '[' << get<0>(s) << ", " << get<1>(s) << ", " << get<2>(s) << ']' << endl;
