0

我正在尝试编写一个程序来计算一个数的阶乘之和。所以如果我给它 3 它会返回 3!+ 2!+ 1!。到目前为止,这是我的代码:

import java.math.BigInteger;
import java.util.Scanner;


public class sumOfFactorial { 

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        System.out.println(sum(n));

    }

    public static BigInteger sum(int n) {
        return factorial(n).add(sum(n-1));
    }

    public static BigInteger factorial(int n) {
        BigInteger x = BigInteger.valueOf(n);
        if (n == 1) return BigInteger.ONE;
        else return x.multiply(factorial(n-1)); //error occurs here
    }
}

出于某种原因,它在指定的位置给了我一个 Stack Overflow 错误。我怎样才能解决这个问题?

4

2 回答 2

3

You are nesting two recursive methods, sum and factorial. However, your sum recursive method doesn't have a base case. Like factorial, it must have a base case. Make sure sum stops recursing at a base case, which in your case appears to be n equals 1.

于 2013-11-04T22:04:41.017 回答
2

one of your problems is here

public static BigInteger sum(int n) {
    return factorial(n).add(sum(n-1));
}

try

public static BigInteger sum(int n) {
    if(n > 1){
      return factorial(n).add(sum(n-1));
    } else if (n < 0){
      throw new IllegalArgumentException("factorials are not defined for negative integers");
    } else {
      return BigInteger.ONE;
    }
}
于 2013-11-04T22:04:57.550 回答