2012-12-22 68 views
-1

我無法找到所寫的內容。我正在嘗試Project Euler#16,在那裏我需要總計2^1000的所有數字。我的程序使用小數字,但數字大約在18位左右,因此打破了。任何幫助?回答問題中的未知因素

public static double digit(double n){ 

    return n % 10; 

} 

public static double sumofDigits(double n){ 

    double sum = 0; 

    while(n > 1){ 

     sum += digit(n); 
     n = Math.floor(n/10); 

    } 

    return sum; 

} 

public static void main(String[] args) { 

    double x = Math.pow(2,1000); 

    double y = 22222222222222222222d; 

    System.out.println(sumofDigits(x)); 

      System.out.println(sumofDigits(y)); 

} 

}

+3

「it break」是什麼意思?你有錯誤嗎?它是什麼? – Ben

回答

5

一個double具有約十六進制數字的精度。由於2次方1000的數字更多(大約300),你根本無法使用雙精度。

看看BigInteger類。

1

你不能在這裏使用double:他們只有有限的精度。 (見Java primitive datatypes

所以Math.pow(2,1000)只計算一些(第一)位數和指數。

你必須使用一些處理任意長整數的庫。 (例如biginteger

0

我明白了。我用代表該十進制數的BigDecimal對象替換了所有雙精度對象,以便實現#的小數精度& &。感謝大家。