Java program to find factorial of a number
Write a java program to find factorial of a number
Here, we will used for loop to loop through all numbers between 1 and the given number num (10), and the product of each number till num is stored in a variable factorial.
We will used long instead of int to store large results of factorial. However, it's still not big enough to store the value of bigger numbers (say 100).
For results that cannot be stored in a long variable, we use BigInteger variable in java.math library.
- Program:
import java.math.BigInteger;
public class Factorial {
public static void main(String[] args) {
int num = 11;
BigInteger factorial = BigInteger.ONE;
for(int i = 1; i <= num; ++i)
{
// factorial = factorial * i;
factorial = factorial.multiply(BigInteger.valueOf(i));
}
System.out.printf("Factorial of %d = %d", num, factorial);
}
}
Output:
Factorial of 11 = 39916800
0 comments