Tuesday, April 8, 2014

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.java
import java.util.Scanner;

/**
 *
 * @author Vijay Apurva
 */
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.?

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 Vijay apurva
 */
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



he output of this program with 50 as input is as:

Enter a number:
50
Factorial of 50 is : 608281864034267560872252163321295376887552831379210240000000000

Can Also calculate  1,00,000 !  :D  :D

No comments:

Post a Comment