Saturday, 6 December 2014

Java Program to find factorial of a number using BigInteger Class

Below program showcase the use of BigInteger class in java to find factorial of a given number x. 
Few constraints are 
T is the no of testcases which is first line of input followed by t lines having single Integer n.
1<=t<=100.
1<=x<=100.

Given x in above range the number is very small. But when we take into account its factorial,neither int or long can hold the result for us .(Try finding factorial of 50 using int or long) 

It is here when BigInteger Class in java becomes handy. Try closer look how we perform various arithmetic operations differently. Here is the code

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;

/**
 *
 * @author Abhishek
 */
public class Factorial {
    public static void main(String[] args)throws Exception {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                String str=br.readLine();
                String str1;
                int n;
                int t = Integer.parseInt(str);
                if(t<1 ||t>100)
                {

                        System.exit(0);
                }
                BigInteger[] result = new BigInteger[t];

                for(int i=0;i<t;i++){
                        str1 = br.readLine();
                        n = Integer.parseInt(str1);
                        if(n<1 || n>100)
                        {

                                System.exit(0);
                        }
                        BigInteger bi = new BigInteger(str1);
                result[i] = Factorial.fact(bi);
                }
                for(BigInteger res:result){
                System.out.println(res);
        }
        }
 
   
 public static BigInteger fact(BigInteger pnum){
        BigInteger lfact;
     
        if(pnum==BigInteger.ZERO)
            return BigInteger.ONE;
        else
        {
            lfact=pnum.multiply(fact(pnum.subtract(BigInteger.ONE)));
        }
        return lfact;
}
}

Lets see the output for t=2 and x=100,99
2
100
99
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
933262154439441526816992388562667004907159682643816214685929638952175999932299156089414639761565182862536979208272237582511852109168640000000000000000000000

Are you surprised looking at the factorials of 99,100

No comments:

Post a Comment