Solution to Project Euler Problem 39: Integer right triangles - If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are exactly three solutions for p = 120. {20,48,52}, {24,45,51}, {30,40,50} For which value of p ≤ 1000, is the number of solutions maximised?
Updated: Jan. 16, 2021 — Training Time: 2 minutes
Overseen by: Archangel Macsika
All Training Resources
Scroll for more menu list
Topic: Project Euler Problem 39: Integer right triangles.
Difficulty: Easy.
Objective: If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are exactly three solutions for p = 120.
{20,48,52}, {24,45,51}, {30,40,50}
For which value of p ≤ 1000, is the number of solutions maximised?
Input: None.
Expected Output: 840.
Sikademy Solution in Java Programming Language
package sikademy;
/**
*
* @author Archangel Macsika
* Copyright (c) Sikademy. All rights reserved
*/
public class SikademyEulerSolution {
public String run() {
int maxPerimeter = 0;
int maxTriangles = 0;
for (int p = 1; p <= 1000; p++) {
int triangles = countSolutions(p);
if (triangles > maxTriangles) {
maxTriangles = triangles;
maxPerimeter = p;
}
}
return Integer.toString(maxPerimeter);
}
private static int countSolutions(int p) {
int count = 0;
for (int a = 1; a <= p; a++) {
for (int b = a; b <= p; b++) {
int c = p - a - b;
if (b <= c && a * a + b * b == c * c)
count++;
}
}
return count;
}
public static void main(String[] args) {
SikademyEulerSolution solution = new SikademyEulerSolution();
System.out.println(solution.run());
}
}
Sikademy Solution in Python Programming Language
#
# @author Archangel Macsika
# Copyright (c) Sikademy. All rights reserved.
#
def compute():
ans = max(range(1, 1001), key=count_solutions)
return str(ans)
def count_solutions(p):
result = 0
for a in range(1, p + 1):
for b in range(a, (p - a) // 2 + 1):
c = p - a - b # c >= b
if a * a + b * b == c * c:
result += 1
return result
if __name__ == "__main__":
print(compute())