我有一些代码,我想执行一个阶乘函数,但是当我在我的代码中实现BigDecimal格式时,它似乎遇到了StackOverflow错误。
对不起,如果问题不是一个正确的问题:)
import java.lang.Math;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Scanner;
public class Factorial {
public static BigDecimal TWO = new BigDecimal("2");
public static BigDecimal ONE = new BigDecimal("1");
public static BigDecimal EvalFact(BigDecimal x, BigDecimal y ){
return x.multiply(y);
}
public static BigDecimal factorial(BigDecimal m , BigDecimal n){
BigDecimal z = m;
if(!m.equals(n)){
BigDecimal p = (n.subtract(m)).divide(TWO,0, RoundingMode.FLOOR);
BigDecimal x = factorial(m, m.add(p));
BigDecimal add_y = ONE.add(m.add(p));
BigDecimal y = factorial(add_y, n);
z = EvalFact(x, y);
}
return z;
}
public static void main(String[] args) {
// TODO code application logic here
int k = 0;
while(k == 0){
Scanner user_input = new Scanner(System.in);
System.out.println("Enter value for n: ");
String sn = user_input.nextLine();
BigDecimal n = new BigDecimal(sn);
BigDecimal fact = factorial(ONE,n);
String sfact = String.valueOf(fact);
System.out.println(sfact);
}
}
}