2013-02-24 52 views
1

我想用fermat的最後一個方程做一個遞歸分析程序,但是它一直返回,表達式是錯誤的我不明白?java中的費馬方程

public class fermatdata 
{ 
    public static void data(int a, int b, int c, int n) 
    { 
     if ((Math.pow(a, n)) + (Math.pow(b, n)) == (Math.pow(c, n))) 
     { 
      System.out.println("Holy smokes, Fermat was wrong!"); 
      return;    
     } 
     else 
     {    
      data(a-1, b-1, c-1, n-1); 
      if (n < 2) 
      {     
       return;     
      } 
      else 
      {     
       data(a-1, b-1, c-1, n-1);     
      }    
     } 
     System.out.println("No, that doesn't work. Fermat was right");   
    }  
    public static void main(String[] args) 
    { 
     System.out.println("Fermat's last theorem stated that the formula a^n + b^n = c^n while n>2 and all of the numbers are integers will never be correct. Here I am going to do an analysis with all the numbers starting at 100,000 and count backwords to 3"); 
     data(100000, 100000, 100000, 100000); 
    } 
} 
+0

你先復發,再檢查'ñ<2'。基本上這是死代碼。 – 2013-02-24 19:37:35

+0

注意雙重比較if((Math.pow(a,n))+(Math.pow(b,n))==(Math.pow(c,n)))''你不應該比較'float/double'用'==' – iTech 2013-02-24 19:39:42

+0

那個死代碼是怎麼回事?它只是停止運行的代碼,如果n小於2,我開始它在100,000,所以不應該它首先運行所有999,997數字? – user1940007 2013-02-24 19:41:26

回答

1

嘗試刪除第一行是這樣的:

 data(a-1, b-1, c-1, n-1); 

好了,現在看什麼Math.pow(100000,100000)給出(無窮大)。我認爲問題在於你使用的值太高(至少n)。

+0

沒有變化,它仍然說明它做了什麼之前 – user1940007 2013-02-24 19:47:10

+0

好吧,現在它給了Infitiy(見我的編輯)。 – vikingsteve 2013-02-24 19:50:14

+0

哈哈,所以他有Infinity + Infinity == Infinity。是的,現在它是有道理的。 – 2013-02-24 19:50:19

0

問題是你使用的能力導致'無窮',因爲數字太大。

由於 '無限==無限' 節目指出,線

((Math.pow(a, n)) + (Math.pow(b, n)) == (Math.pow(c, n))) 

是正確的