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