Calculating Large
Factorial
Factorial of a non-negative number n is denoted by n! and it
is the product of all positive integers less than or equal to n. Hence
factorial of 5 is:
1*2*3*4*5=120.
Factorial in a programming
language can be calculated using a loop or a recursive procedure. But once the
factorial exceeds the largest number supported by standard data type like int or
long, it rolls to the negative minimum. Hence sometimes we get weird output. For an example, factorial of 50 is very large
and it overflows the largest number supported by int or long as obvious by the
following program:
//Factorial.java import java.util.Scanner; /** * * @author VIK VIKKU VIKASHVVERMA */ public class Factorial { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("Enter the number:"); int num=sc.nextInt(); int fact=1; for (int i = 1; i <=num; i++) { fact*=i; } System.out.println("Factorial of "+num+" is : "+fact); }//main(-) }//Factorial
The output of the program is as below:
Enter the number:
50
Factorial of 50 is : 0
When we change the data type of fact to long to increase size and
run the same program we get the output as shown below:
Enter the number:
50
Factorial of 50 is : -3258495067890909184
No primitive data type of any language can be used to calculate large factorial. So how can we get the factorial of 50 or other numbers perfectly.?
No primitive data type of any language can be used to calculate large factorial. So how can we get the factorial of 50 or other numbers perfectly.?
In JAVA, we have BigInteger class in java.math package which can be
used to store very large number and we will be using this class to calculate
factorial of such numbers. So here goes a java program to calculate factorial
of 50 or 100 or other numbers:
//FactorialDemo.java import java.math.BigInteger; import java.util.Scanner; /** * * @author VIK VIKKU VIKASHVVERMA */ class Factorial { int num; BigInteger bi = new BigInteger("1"); public void read() { System.out.println("Enter a number:"); Scanner sc = new Scanner(System.in); num = sc.nextInt(); }//read() public void process() { if (num < 0) { System.out.println("Invalid number!"); System.exit(1); } for (int i = 1; i < num; i++) { bi = bi.multiply(BigInteger.valueOf(i)); } }//process() public void display() { System.out.println("Factorial of " + num + " is : " + bi); }//display() }//Factorial public class FactorialDemo { public static void main(String[] args) { Factorial f=new Factorial(); f.read(); f.process(); f.display(); }//main(-) }//FactorialDemo
The output of this program with 50 as input is as:
Enter a number:
50
Factorial of 50 is : 608281864034267560872252163321295376887552831379210240000000000
Also the factorial of 100 is:
Enter a number:
100
Factorial of 100 is :
933262154439441526816992388562667004907159682643816214685929638952175999932299156089414639761565182862536979208272237582511852109168640000000000000000000000