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