Reputation: 127
I'm trying to write a program that calculates the sum of a factorials up to a number. So if I gave it 3 it would return 3! + 2! + 1!. Here is my code so far:
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
}
}
For some reason it gives me a Stack Overflow error at the indicated spot. How can I fix this?
Upvotes: 0
Views: 141
Reputation: 8269
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;
}
}
Upvotes: 2
Reputation: 178263
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
.
Upvotes: 3