English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
在此程序中,您将学习使用Java中的for和while循环查找数字的阶乘。
Le facteuriel des nombres positifs est donné par l'expression n :
factorial de 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 de %d = %d", num, factorial); } }
When running the program, the output is:
Factorial de 10 = 3628800
在此程序中,我们使用for循环遍历了1et le nombre donné num(10) entre tous les nombres, chaque produit des nombres jusqu'à num et stocké dans la variable factorial.
Nous utilisons long plutôt que int pour stocker les résultats de la factorielle grands, mais cela ne suffit pas pour stocker la valeur des plus grands nombres (par exemple100的阶乘)
对于无法存储在long变量中的结果,我们使用在java.math库中声明的BigInteger变量。
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("La factorielle de %d = %d", num, factorial); } }
When running the program, the output is:
3La factorielle de 0 = 265252859812191058636308480000000
Ici, nous utilisons BigInteger pour stocker la factorielle.
En raison de*Ne peut pas être utilisé avec BigInteger, donc nous utilisons multiply() pour ce produit. De plus, num doit être converti en BigInteger pour la multiplication.
Parce que*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 the 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.