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,410
  • 6
  • 26
  • 47
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
  • 122,468
  • 25
  • 185
  • 269
Samir Vyas
  • 442
  • 2
  • 6
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
  • 36,363
  • 4
  • 24
  • 39