Search code examples
javabigintegerfactorial

BigInteger Factorial Table 1-30


I'm supposed to print a table of the integers from 0 to 30 along with their factorials. I tried, but I keep getting an error saying BigInteger(long) has private access in BigInteger? Thoughts?

public static void main(String[] args) {
    int x = 0;
    for (x = 0; x < 31;) {
        System.out.println(x + " " + factorial(x));

        x = x + 1;

    }
}

/*
       public static int factorial (int n) {   
       if (n == 0) {
             return 1;
        } else {
            return n * factorial (n-1);
           }
        }
         // error occuring at 13! could be because the number becomes too great for int to handle, resulting in an overflow error.

     }*/
public static BigInteger factorial(int n) {
    if (n == 0) {
        return BigInteger.ONE;
    } else {

        BigInteger result = new BigInteger(n).multiply(factorial(n - 1));(error here)

        return result;
    }
    //return new BigInteger(n) * factorial(n - 1);
}

Solution

  • There is a BigInteger constructor taking a long, but it is private so can only be called from the BigInteger class itself.

    You need to use BigInteger.valueOf(n) instead.