Java factorial program with recursion and BigIntegers

# Java factorial program with recursion and BigIntegers

Another initiative at work expects me to have a certain amount of Java knowledge. Oh well. Here are some good resources I am currently going through:

Learneroo’s first chapter has a factorial method recursively. No biggie. I wrote a quick program, ran and tested it for small values. When I tried it for ‘100’, though:

Enter a number for which I will find the factorial:
100
0

Oops. The same program worked fine with Python, what was I doing wrong? A quick check showed that my program returned the result as an int. The highest Int you can get is 2^(31)-1. So, enter the BigInteger class. It is not a native data type and I had to tweak the program a bit to handle it. This is what it shows as the output now:

Enter a number for which I will find the factorial:
100
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

And here is the full program:

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

public class Factorial {

public static void main(String[] args) {
Scanner read = new Scanner(System.in);
System.out
.println(“Enter a number for which I will find the factorial:”);
int num = read.nextInt();
Factorial test = new Factorial();
BigInteger result = test.findfact(num);
System.out.println(result);
read.close();
}

public BigInteger findfact(int n) {
if (n == 1) {
return BigInteger.ONE;
} else {
return BigInteger.valueOf(n).multiply(findfact(n – 1));
}
}
}

Comments are closed.