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 following 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); } }
Wenn das Programm ausgeführt wird, lautet die Ausgabe:
Factorial of 10 = 3628800
In this program, we used a for loop to traverse1and the given number num(10) of all numbers between them, each of which is multiplied until num and 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); } }
Wenn das Programm ausgeführt wird, lautet die Ausgabe:
3The factorial of 0 = 265252859812191058636308480000000
Here, we use BigInteger instead of long to store the factorial.
Because*Since BigInteger cannot be used together with BigInteger, we use its multiply() method for this product. Additionally, num should be explicitly converted to BigInteger for multiplication.
Weigh*Kann nicht mit BigInteger verwendet werden, daher verwenden wir multiply() für die Berechnung. Darüber hinaus sollte num in BigInteger umgewandelt werden, um die Multiplikation durchzuführen.
Genauso können wir auch die while-Schleife verwenden, um dieses Problem zu lösen.
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 Fakultät = %d", num, factorial); } }
Wenn das Programm ausgeführt wird, lautet die Ausgabe:
5 Fakultät = 120
Im obigen Programm müssen wir den Wert von i im Schleifenkörper erhöhen, anders als in der for-Schleife.
Obwohl beide Programme technisch korrekt sind, ist es in diesem Fall am besten, eine for-Schleife zu verwenden. Dies liegt daran, dass die Anzahl der Iterationen (bis zu num) bekannt ist.