English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn to use for and while loops in Java to find the factorial of a number.
The factorial of a positive number is given by the formula n!
factorial of n (n!) = 1 * 2 * 3 * 4 * ... * n
public class Factorial { public static void main(String[] args) { int num = 10; long factorial = 1; for(int i = 1; i <= num; ++i) { // factorial = factorial * i; factorial *= i; } System.out.printf("Factorial of %d = %d", num, factorial); } }
When running the program, the output is:
Factorial of 10 = 3628800
In this program, we use a for loop to traverse1and the given number num(10) and the product of each number up to num, which is stored in the variable factorial.
We use long instead of int to store the large results of the factorial. However, it is still not large enough to store the value of larger numbers (such as10The factorial of 0)
For results that cannot be stored in a long variable, we use the BigInteger variable declared in the java.math library.
import java.math.BigInteger; public class Factorial { public static void main(String[] args) { int num = 30; BigInteger factorial = BigInteger.ONE; for(int i = 1; i <= num; ++i) { // factorial = factorial * i; factorial = factorial.multiply(BigInteger.valueOf(i)); } System.out.printf("The factorial of %d = %d", num, factorial); } }
When running the program, the output is:
3The factorial of 0 = 265252859812191058636308480000000
Here, we use BigInteger to store the factorial instead of long.
Due to*Since BigInteger cannot be used together, we use its multiply() method for this product. Additionally, num should be explicitly converted to BigInteger for multiplication.
Because*Cannot be used with BigInteger, so we use multiply() for the calculation. Additionally, num should be converted to BigInteger for the multiplication operation.
Similarly, we can also use a while loop to solve this problem.
public class Factorial { public static void main(String[] args) { int num = 5, i = 1; long factorial = 1; while(i <= num) { factorial *= i; i++; } System.out.printf("%d Factorial = %d", num, factorial); } }
When running the program, the output is:
5 Factorial = 120
In the above program, unlike the for loop, we must increase the value of i within the loop body.
Although both programs are technically correct, it is best to use a for loop in this case. This is because the number of iterations (up to num) is known.