私はすべてのピタゴラスの四重奏を取得しようとしています:
a^2 + b^2 + c^2 = d^2 when a, b, c <= 1000
、
私のコードはそれらすべてを生成します ( 85490
) が、約10 分かかります。
実行時間を短縮しようとしています。どうすれば実行時間を改善できますか? 任意の提案をお願いします。
これが私のコードです。
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;
}