I'm trying to get all the Pythagorean quadruples:
a^2 + b^2 + c^2 = d^2 when a, b, c <= 1000
,
My code generates all of them (85490
) but it takes around 10 minutes.
I am trying to reduce the execution time. How can I improve the execution time?. Any suggestion please.
Here is my code.
static int isSquare(int n)
{
int m = (int) Math.sqrt(n);
return m * m == n ? m : 0;
}
static List<List<Integer>> allQuadraples = new ArrayList<>();
static int findQuadraples(int range)
{
int total = 0;
for (int a = 1; a <= range; a++)
for (int b = 1; b <= range; b++)
for (int c = 1; c <= range; c++)
{
int sum = a * a + b * b + c * c;
int d = isSquare(sum);
if (d != 0) // a possible Quadruple
{
List<Integer> oneQuadraple = new ArrayList<>(Arrays.asList(a, b, c, d));
Collections.sort(oneQuadraple); // sorting before insertion for comparing later
if (!allQuadraples.contains(oneQuadraple))
{
System.out.println(oneQuadraple);
allQuadraples.add(oneQuadraple);
total++;
}
}
}
return total;
}