Recent Posts

Tuesday 30 June 2015

Finding Factorial using the BigInteger in JAVA

Up to Schooling we may only find factorial up to 25 but in real engineering we may have to deal with the largest numbers where the usual datatypes may not work. In Java , BigInteger is the pre-defined class we use in order to deal with those numbers.

Here in our example, using BigInteger we are finding factorial for larger Numbers.

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

public class HelloWorld {
    @ SuppressWarnings ("deprication")
    /*  The above line suppress the deprication warnings */
    public static void main(String[] args) {
    try{
        Scanner sc=new Scanner(System.in);
        int tests=Integer.parseInt(sc.next());
        BigInteger num,sum;
        String res;
        while(tests--!=0)
        {
        sum=new BigInteger("1");
        num=new BigInteger(sc.next());
        while(num.compareTo(new BigInteger("0"))!=0){
        sum=sum.multiply(num);
        num=num.subtract(new BigInteger("1"));
        }
        res+=sum+"\n";
        }
        System.out.println(res);
    }
    catch(Exception e){ System.out.println(e.getMessage()); }
    }
}

Smart Siva

Author & Editor

In Life every second is important, In programming every line of code is important.

0 comments:

Post a Comment

 
biz.