2011-10-14 26 views
3

我一直在試圖解決Problem 20在項目歐拉:找到數字100中的數字總和! (我while循環不會停止)

N!意思是n(n 1)... 3 * 2 * 1 例如,10! = 10 * 9 ... 3 * 2 * 1 = 3628800, 以及數字10中的數字之和!是3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. 找到數字100的總和!

這就是我到目前爲止所提出的。我已經得到了這個代碼的正確答案(這是648),但我有點OC,因爲我的代碼是一個無限循環。在while循環內結果變爲0後,它不會停止。任何人都可以幫我解決這個問題嗎?

public static BigInteger problem20(int max){ 
    BigInteger sum = BigInteger.valueOf(0); 
    BigInteger result = BigInteger.valueOf(1); 
    BigInteger currentNum = BigInteger.valueOf(0); 

    for(long i = 1; i<=max; i++){ 
     result = result.multiply(BigInteger.valueOf(i)); 
     //System.out.println(result); 
    } 

    while (!result.equals(0)) { 
     sum = sum.add(result.mod(BigInteger.valueOf(10))); 
     result = result.divide(BigInteger.valueOf(10)); 
     System.out.println(sum + " "+ result); 
    } 
    return sum; 
} 

回答

5

這就是問題:

while (!result.equals(0)) 

resultBigInteger,這決不會等於一個Integer。嘗試使用

while (!result.equals(BigInteger.ZERO)) 
+0

OMG的總和!我知道它必須沿着這些路線而行! > _ <非常感謝! <3 –

0

請修改代碼以:

while (!result.equals(BigInteger.valueOf(0))) { 
     sum = sum.add(result.mod(BigInteger.valueOf(10))); 
     result = result.divide(BigInteger.valueOf(10)); 
     System.out.println(sum + " "+ result); 
    } 
1

另一種可能性是使用while (fact.compareTo(BigInteger.ZERO) > 0)

我建議您在可能的地方使用BigInteger.ZERO,BigInteger.ONEBigInteger.TEN

實施例:

import java.math.BigInteger; 

public class P20 { 

    public static void main(String[] args) { 
     System.out.println(getSum(100)); 
    } 

    private static long getSum(int n) { 
     BigInteger fact = BigInteger.ONE; 
     for (int i = 2; i <= n; i++) { 
      fact = fact.multiply(BigInteger.valueOf(i)); 
     } 
     long sum = 0; 
     while (fact.compareTo(BigInteger.ZERO) > 0) { 
      sum += fact.mod(BigInteger.TEN).longValue(); 
      fact = fact.divide(BigInteger.TEN); 
     } 
     return sum; 
    } 

} 

它需要4毫秒

它可以用下面的觀測加以改進:

  • 總和不被零影響=>你不需要通過10和100,而不是20,30,繁衍......這是足以使用2,3,...。當然,您可以使用以下事實概括此規則5*k * 2*j可以被10整除。
0

這裏是做同樣的事情的另一種方法。在這裏,計算總和的複雜度是O(1)。

import java.math.BigInteger; 
import java.util.ArrayList; 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

public class Main{ 
    public static void main(String[] args){ 
BigInteger b = BigInteger.valueOf(1); 
     for(int i=2;i<=5;i++){ 
      b = b.multiply(BigInteger.valueOf(i)); 
     } 
     //System.out.println(b); 

計算如下

final BigInteger NINE = BigInteger.valueOf(9); 
      if(b == BigInteger.ZERO){ 
       System.out.println(b); 
      }else if(b.mod(NINE) == BigInteger.ZERO){ 
       System.out.println(NINE); 
      }else{ 
       System.out.println(b.mod(NINE)); 
      } 

     }` 
}