Java 阶乘编程挑战

Java 阶乘编程挑战,java,math,Java,Math,我最近完成了一项编程挑战,挑战我们获得2015年的阶乘。在计算阶乘后,需要对整数中的所有数字求和(在本例中为BigInteger) 完成后,我得到的结果是:23517 然而,当我提交给教授时,他说正确的结果是:26532 我似乎根本找不到问题。我已经核对了多个资料来源,到目前为止,一切似乎都表明我是对的。有人能找到我的代码哪里出错了吗 import java.math.BigInteger; class toymeister { public static void main(Str

我最近完成了一项编程挑战,挑战我们获得2015年的阶乘。在计算阶乘后,需要对整数中的所有数字求和(在本例中为BigInteger)

完成后,我得到的结果是:23517

然而,当我提交给教授时,他说正确的结果是:26532

我似乎根本找不到问题。我已经核对了多个资料来源,到目前为止,一切似乎都表明我是对的。有人能找到我的代码哪里出错了吗

import java.math.BigInteger;

class toymeister {

    public static void main(String[] args){
        System.out.println("The sum is: " + SumOf(FactorialOf(2015)));
    }

    public static BigInteger FactorialOf(int x){
        BigInteger Answer, intConvert;

        intConvert = new BigInteger("0");
        Answer = new BigInteger("1");       

        for(int i=1; i<=x;i++){
            intConvert = intConvert.valueOf(i);
            Answer = Answer.multiply(intConvert);
        }

        System.out.println("The Factorial Of " + x + " is: " + Answer);

        return Answer;
    }

    public static BigInteger SumOf(BigInteger y){
        BigInteger Sum = new BigInteger("0");

        while(y.compareTo(BigInteger.ZERO) > 0) {
            Sum = Sum.add(y.mod(BigInteger.TEN));
            y = y.divide(BigInteger.TEN);
        }

        return Sum;
    }
}
import java.math.biginger;
玩具匠{
公共静态void main(字符串[]args){
System.out.println(“总和为:+SumOf(FactorialOf(2015)));
}
公共静态biginger FactorialOf(int x){
大整数答案,整数转换;
intConvert=新的大整数(“0”);
答案=新的大整数(“1”);
对于(int i=1;i 0){
Sum=Sum.add(y.mod(biginger.TEN));
y=y.divide(biginger.TEN);
}
回报金额;
}
}
答案是23517。不过,您可以简化代码:

public static BigInteger factorialOf(int x) {
    BigInteger answer = BigInteger.ONE;
    for(int i = 1; i <= x; i++) {
        answer = answer.multiply(BigInteger.valueOf(i));
    }
    System.out.println("The Factorial Of " + x + " is: " + answer);
    return answer;
}

public static int sumOf(BigInteger y) {
    String digits = y.toString();
    int sum = 0;
    for(int i = 0, n = digits.length(); i<n; i++) sum += digits.charAt(i)-'0';
    return sum;
}

首先,请遵循:变量名应以小写字母开头。。。23517是正确的,你的教授错了。你的回答是正确的。我支持这里的评论。你的教授错了。我投票结束这个问题,因为问题在教授的椅子和键盘之间:像这样的圆周率。(+1). 我可能会使用
orElse(biginger.ONE)
来获得
x==0
的正确结果。感谢您提供了简化代码的其他方法。我真的认为我的代码简化得很好@保罗·博丁顿:说得好
public static BigInteger factorialOf(int x) {
    return IntStream.rangeClosed(1, x).mapToObj(BigInteger::valueOf)
        .reduce(BigInteger::multiply).orElse(BigInteger.ONE);
}
public static int sumOf(BigInteger y) {
    return y.toString().chars().map(i -> i-'0').sum();
}