Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Factorial in Java

Tags:

java

factorial

I've been using this factorial program for Java:

public static long factorial(int a) {

    if(a<1) {
        return 1;
    }
    long result=1;
    long x=a;
    while(x>1) {
        result*=x;                     
        x--;
    }
    return result;
}

However, it seems to "break" and return a negative number after the factorial of 25. It returns a negative number for a while then just returns "0."

Am I doing anything wrong that is causing this?

like image 717
Toby Avatar asked Dec 07 '22 15:12

Toby


2 Answers

You've overflowed long.
Use BigInteger instead.

like image 68
SLaks Avatar answered Dec 20 '22 14:12

SLaks


25! = 15511210043330985984000000

The maximum value of a long in Java is 2^63-1 = 9223372036854775807 (source).

25! is about 1.7*10^6 the size of the largest value a long can store in Java. Use a BigInteger instead.

like image 23
jonmorgan Avatar answered Dec 20 '22 13:12

jonmorgan