Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
654 views
in Technique[技术] by (71.8m points)

java - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)));
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...