0

これまでのところ、私のコードは問題なく動作しますが、速度を上げる方法が必要です。ユーザーが max_values を 25000 に入力すると、約 1.81 秒かかり、1 秒未満にする必要があります。トリプルメソッドを最適化するために最善を尽くしましたが、他に何をすべきかわかりません。

import java.util.InputMismatchException;
import java.util.Scanner;

public class Pythagorean {

public static void triples(int max_values){
    int x = 0;
    for(int c = 5; c <= max_values; c++){
        int cTwo = c * c;
        int b = c - 1;
        for (int a = 0;a <= cTwo - b*b;a++){
            if (a*a + b*b == cTwo){
                x++;
                System.out.println(x + ") " + a + " " + b + " " +c);
            }
        }
    }
}

public static void main(String[] args){
    System.out.println("--- Pythagorean Triple Generator ---");
    System.out.println();
    Scanner input = new Scanner(System.in);
    int max_value = 0;
    System.out.print("Enter max value for c: ");
    try{
        max_value = input.nextInt();
    } catch (InputMismatchException ime) {
        input.nextLine();
        System.err.println("Error: Input is not an integer.");
        System.exit(1);
    }
    input.close();
    long start = System.currentTimeMillis();
    triples(max_value);
    double elapsed = (System.currentTimeMillis() - start)/ 1000.0;
    System.out.println("Searching complete...");
    System.out.printf("Elpased time: %.3f\n", elapsed);
}
}
4

2 に答える 2

3

これは、私の PC で 0.999 秒で実行されました。

シングルStringBuilderを使用してすべての出力を収集printlnし、最後に 1 つだけを実行します。

public static void triples(final int max_values)
{
    int x = 0;
    final StringBuilder sb = new StringBuilder(24000);
    for (int c = 5; c <= max_values; c++)
    {
        final int cTwo = c * c;
        final int b = c - 1;
        final int bTwo = b * b;
        final int cTwoLessB = cTwo - bTwo;

        for (int a = 0; a <= cTwoLessB; a++)
        {
            if (a * a + bTwo == cTwo)
            {
                x++;
                sb.append(x);
                sb.append(") ");
                sb.append(a);
                sb.append(" ");
                sb.append(b);
                sb.append(" ");
                sb.append(c);
                sb.append("\n");
            }
        }
    }
    System.out.println(sb.toString());
}
于 2012-10-25T21:22:12.380 に答える
1

ボトルネックの可能性が最も高いSystem.out.printlnです。コンソールへの書き込みには時間がかかることがよくあります。

 for (int a = 0;a <= cTwo - b*b;a++){
            if (a*a + b*b == cTwo){
                x++;
                System.out.println(x + ") " + a + " " + b + " " +c);//Do you really need this?
            }
        }

おそらく、それをコレクションに保存し、ループが完了した後に印刷を行うことができます (または、提案されているように Stringbuilder を使用します)。

いくつかの最適化:

int multiplyB = b*b ;//multiplication can also be slow. 
for (int a = 0;a <= cTwo - multiplyB;a++){
            if (a*a + multiplyB == cTwo){
                ++x;//use preincrement operator
              str.append(x ).append(") ").append(a).append( " ").append(b).append(" ").append(c).append("\n");

            }
 }
于 2012-10-25T21:04:03.353 に答える