2013-04-21 202 views
0

好了,我具有由下面的代碼所定義的在Collat​​z序列長度:不同數量的有人能告訴我爲什麼我會得到這個輸出嗎?

private static int count = 0; 

    private static int collatz(int n){ 
     count++; 
     if(n > 1){ 
      if(n % 2 == 0){ 
       return collatz(n/2); 
      } 
      return collatz(3*n+1); 
     } 
     return count-1; 
    } 

現在,我檢查了輸出(例如打印(在Collat​​z(3000))=> 48),以驗證算法正常工作。我用various sites來做到這一點,但有一個號碼拒絕工作。這個數字正是ProjectEuler第14個問題的解決方案。這是如何可能的,與其他數字我得到正確的結果(正確的鏈長度),而837799產生不同的結果:58,而不是524.

+7

只是一個猜測:也許這個數字之所以選擇非常明確,因爲它產生的序列包含大量那溢出一個Java'int'? – Mat 2013-04-21 18:48:33

+1

你試過用久嗎? – 2013-04-21 18:48:54

+0

馬特的權利,使用'長'看。 – 2013-04-21 18:49:07

回答

1

正如其他指出在評論中,這是一個溢出問題。你可以通過打印函數調用的參數來發現它。

變化intlong,甚至更好,要絕對確保它不會溢出,使用BigInteger

private static int collatz(BigInteger n) { 
    count++; 
    if (n.compareTo(BigInteger.ONE) > 0) { 
     if (!n.testBit(0)) // even 
      return collatz(n.divide(BigInteger.valueOf(2))); 

     else 
      return collatz(n.multiply(BigInteger.valueOf(3)).add(BigInteger.ONE)); 
    } 
    return count - 1; 
} 

public static void main(String[] args) { 
    System.out.println("res: " + collatz(BigInteger.valueOf(837799))); 
} 
相關問題