找到数字100中的数字总和! (我的while循环不会停止)

时间:2011-10-14 16:35:32

标签: java biginteger factorial

我一直在努力解决Project Euler中的Problem 20

  

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;
}

4 个答案:

答案 0 :(得分:5)

这是问题所在:

while (!result.equals(0))

resultBigInteger,永远不会等于Integer。尝试使用

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

答案 1 :(得分:1)

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

我建议您尽可能使用BigInteger.ZEROBigInteger.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 ms

可以使用以下观察结果进行改进:

  • 总和不受零的影响=&gt;你不需要乘以10和100而不是20,30,......它足以使用2,3,.......当然,您可以使用以下事实来概括此规则5*k * 2*j可被10整除。

答案 2 :(得分: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);
    }

答案 3 :(得分: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));
            }

        }`
}
相关问题