0

到目前为止,我的代码运行良好,但我需要一种方法来加速它。当用户输入 max_values 为 25000 时,大约需要 1.81 秒,我需要它小于一秒。我尽力优化我的三元组方法,但我不知道还能做什么。

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在最后只做一个。

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 回答