Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which data type or data structure to choose to calculate factorial of 100?

I thought of writing a program to evaluate factorial of a given integer.

Following basics I wrote the below code in java :

long fact(int num){
if(num == 1)
 return 1;
else
 return num*fact(num-1);
}

But then I realized that for many integer input the result may not be what is desired and hence for testing directly gave input as 100.

My doubt was true as Result I got was "0"(cause result might be out of range of long).

So,I am just curious and eager to know as how may I make my program work for inputs<=150.

I would appreciate any valid solution in C programming language or Java.

like image 289
Abhinav Avatar asked Mar 04 '13 15:03

Abhinav


People also ask

Which data type can store 100 factorial?

use double instead of long long int, as for 100!, long long int is too short to hold the result.

How do you calculate 100 factorial?

The answer of what is the factorial of 100 The approximate value of 100! is 9.3326215443944E+157. The number of trailing zeros in 100! is 24. The number of digits in 100 factorial is 158.

What is factorial in data structure?

The factorial, symbolized by an exclamation mark (!), is a quantity defined for all integer s greater than or equal to 0. For an integer n greater than or equal to 1, the factorial is the product of all integers less than or equal to n but greater than or equal to 1.

What is the easiest way to find the factorial of a number?

To find the factorial of a number, multiply the number with the factorial value of the previous number. For example, to know the value of 6! multiply 120 (the factorial of 5) by 6, and get 720. For 7!


1 Answers

BigInteger is your class. It can store integers of seemingly any size.

    static BigInteger fact(BigInteger num) {
        if (num.equals(BigInteger.ONE))
            return BigInteger.ONE;
        else
            return num.multiply(fact(num.subtract(BigInteger.ONE)));
    }
like image 160
poitroae Avatar answered Nov 14 '22 22:11

poitroae