0
 long fact= 1;
 for(int i=1;i<=n;i++){
     fact=fact*i;
 }
 System.out.println(fact);

The code should produce factorial of large numbers, for example 25. But the output is not correct.

Gaurav Jeswani
  • 4,134
  • 6
  • 23
  • 41
QUEST275
  • 23
  • 7

3 Answers3

3

Like Samir Vyas said "It exceeds the number range which can be represented by java long type."
If you want to bypass this limit, you will need to use a BigInteger or a BigDecimal.
You can find more information on this question Large Numbers in Java

Vincent VDV
  • 31
  • 1
  • 6
2

It exceeds the number range which can be represented by java long type.

https://docs.oracle.com/javase/8/docs/api/java/lang/Long.html

Pshemo
  • 118,400
  • 24
  • 176
  • 257
Samir Vyas
  • 421
  • 2
  • 4
0

Try this.

int n = 30;                                
System.out.printf("%d! = %,d%n",n,fact(n));

public static BigInteger fact(int fact) {        
    BigInteger f = BigInteger.valueOf(fact);     
    while (--fact > 1) {                         
        f = f.multiply(BigInteger.valueOf(fact));
    }                                            
    return f;                                    
}

Prints

30! = 265,252,859,812,191,058,636,308,480,000,000
         

For more information on arbitrary precision math check out BigInteger and BigDecimal in the JDK API.

WJS
  • 30,162
  • 4
  • 20
  • 36