2012-10-25 29 views
0

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

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); 
} 
} 
+0

写入控制台很慢。如果你不需要循环,跳过它。如果您仍然需要更好的表现,请转到C. – GolezTrol

+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()); 
} 
+0

是的,谢谢现在工作得更快。我会upvote,但我需要15代表非常抱歉。 – user1775500

+0

@DNA不错,+1 .. –

+1

@ user1775500你可以选择这个作为你的答案,这将比upvote更值得。 – 16dots

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"); 

      } 
} 
+0

-1这不回答OP的问题。 – NominSim

+0

是的。它可以帮助加快速度。 –

+0

是的,我确实需要那个或我该如何打印出来?虽然这是一个很好的建议,但如果不需要打印 – user1775500