加速毕达哥拉斯三重计算器

时间:2012-10-25 21:01:33

标签: java

到目前为止,我的代码运行良好,但我需要一种方法来加快速度。当用户输入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);
}
}

2 个答案:

答案 0 :(得分:3)

这只是在我的电脑上以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());
}

答案 1 :(得分: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");

            }
 }