I have created what was a rather simple piece of code to calculate the factorial of a number, although I wanted to ensure that my program could calculate the factorial of any given number. To do this, the only data type I thought was relevant was BigInteger. The problem I had with this was that my code quickly became quite messy, nevertheless, it works! I have chosen to take the approach of using recursion to calculate the answer, as I felt it is the best way to keep the code short and efficient.I have looked at others code on this site, and read the reviews given, and it seems most users have chosen to use int, which isn't a problem, although as I say, I don't want an IntegerOverflow to occur when the user gives their input.Is there a way to clean up this code; or make it more efficient?import java.math.BigInteger;public class Factorial {    public static void main (String [] args) {        java.util.Scanner sc = new java.util.Scanner(System.in);        System.out.print(Enter an integer to calculate the factorial of: );        BigInteger temp = sc.nextBigInteger();        sc.close();        System.out.println(temp + ! =  + calculateFactorial(temp));    }    private static BigInteger calculateFactorial (BigInteger n) {        if (n.compareTo((new BigInteger(1))) ==  -1) {            return new BigInteger(1);        } else {            return (n.multiply(calculateFactorial(n.subtract(new BigInteger(1)))));        }    }}
Calculating the factorial of any number
java;performance;recursion
Fully qualified class names are rarely written in the body of the code; they are almost always imported instead.If you want to close the Scanner, use a try-with-resources block.  It calls close() even in the case of an intervening exception, and it is easier to see where the Scanner is valid.temp is nearly never a good variable name.  Even n would be better: it's a conventional variable name for some kind of integer.It would be good practice to suppress the default constructor by defining a private Factorial() {} constructor.calculateFactorial would be better named factorial, and it should probably be public.Are you really going to compute the factorial of a number larger than Long.MAX_VALUE?  You'll run into problems with stack overflow from recursion.  (You should use iteration instead.)  Even if that worked, you would still be dealing with numbers so large that I'm not sure BigInteger could handle.