Posted in java, programming

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:

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:

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(;
                .println(“Enter a number for which I will find the factorial:”);
        int num = read.nextInt();
        Factorial test = new Factorial();
        BigInteger result = test.findfact(num);

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