繁体   English   中英

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

[英]Find the sum of the digits in the number 100! (My while loop would not stop)

我一直在努力解决Euler项目中的问题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;
}

这就是问题:

while (!result.equals(0))

result是一个BigInteger ,永远不会等于Integer 尝试使用

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

另一种可能性是使用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毫秒

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

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

这是另一种做同样的方法。在这里,计算总和的复杂度是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));
            }

        }`
}

请将您的代码修改为:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM