2015-07-10 136 views
2

所以我需要幫助計算勾股數,基本上我所要的輸出是這樣的:勾股數計算的Java

3 4 5 
5 12 13 
6 8 10 
7 24 25 

ETC.

我需要計算部分的幫助,並確保我沒有重複(即5 12 13和12 5 13)。

想法?有人能帶領我走向正確的方向嗎?

這裏是我的代碼,我到目前爲止有:

package cs520.hw1; 

public class Triples { 

     public static void main(String[] args) 
     { 
      int x1, x2, x3; 

      for(x1 = 1; x1 < 100; x1++) 
      { 
       for(x2 = 1; x2 < 100; x2++) 
       { 
        for(x3 = 1; x3 < 100; x3++) 
        { 
         int a= x1, b=x2, c=x3; 

         if((Math.sqrt(a) + Math.sqrt(b)) == Math.sqrt(c)) 
         { 
          if(a < b) 
          { 
           System.out.println(x1 +" "+ x2 +" "+ x3); 
          } 
         } 
        } 
       } 
      }  
     } 
    } 
+0

什麼是你的代碼的問題?你有什麼樣的錯誤?它沒有返回預期的結果嗎?你有什麼問題? – Micho

+0

這與你的問題無關,但是有一個'Math.hypot(a,b)'函數來計算'sqrt(a * a + b * b)'。在你的示例代碼中可能沒有關係,請注意你;然而,如果你有非常多的數字,它可能會有所作爲。 – celticminstrel

回答

0

您需要將呼叫變爲Math.sqrt(n)Math.pow(n, 2),其中n = A,B,C。

所以,代碼變得

package cs520.hw1; 

public class Triples { 

public static void main(String[] args) 
{ 
     int x1, x2, x3; 

     for(x1 = 1; x1 < 100; x1++) 
     { 
      for(x2 = 1; x2 < 100; x2++) 
      { 
       for(x3 = 1; x3 < 100; x3++) 
       { 
        int a= x1, b=x2, c=x3; 

        if((Math.pow(a, 2) + Math.pow(b, 2)) == Math.pow(c, 2)) 
        { 
         if(a < b) 
         { 
          System.out.println(x1 +" "+ x2 +" "+ x3); 
         } 
        } 
       } 
      } 
     }  
    } 
} 
0

示例代碼:

public class QuickTester { 

    // Change MAX to whatever value required 
    private static final int MAX = 25; 

    public static void main(String[] args) { 

     int a, b, c; 

     for(a = 1; a < MAX; a++) 
     { 
      for(b = a; b < MAX; b++) 
      { 
       for(c = b; c < MAX; c++) 
       { 
        if((Math.pow(a, 2) + Math.pow(b, 2)) 
          == Math.pow(c, 2)) 
        { 
         System.out.printf("%d %d %d\n", 
           a, b, c); 
        } 
       } 
      } 
     } 
    } 
} 

輸出(用於MAX爲25,而不是100):

3 4 5 
5 12 13 
6 8 10 
8 15 17 
9 12 15 
12 16 20 

注:

  • 要確保你沒有得到(5 12 13 12 5月13日),只需確保一個< b <℃。
  • 使用(Math.pow(A,2)+ Math.pow(B,2))== Math.pow(C,2)找到了三胞胎
+0

或'Math.hypot(a,b)== c'。 – celticminstrel

+0

@celticminstrel好的,我想這樣也可以。 – Gosu