用Java写一个1阶乘到20阶乘的代码并且输出答案
时间: 2024-05-03 16:21:50 浏览: 121
```
public class Factorial {
public static void main(String[] args) {
for (int i = 1; i <= 20; i++) {
long factorial = 1;
for (int j = 1; j <= i; j++) {
factorial *= j;
}
System.out.println(i + "! = " + factorial);
}
}
}
```
输出结果:
```
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
11! = 39916800
12! = 479001600
13! = 6227020800
14! = 87178291200
15! = 1307674368000
16! = 20922789888000
17! = 355687428096000
18! = 6402373705728000
19! = 121645100408832000
20! = 2432902008176640000
```
相关问题
用Java写一个1阶乘到20阶乘之和的代码并且输出答案
```
public class FactorialSum {
public static void main(String[] args) {
long sum = 0;
long factorial = 1;
for (int i = 1; i <= 20; i++) {
factorial *= i;
sum += factorial;
}
System.out.println("1! + 2! + 3! + ... + 20! = " + sum);
}
}
```
输出结果为:
```
1! + 2! + 3! + ... + 20! = 2561327494111820313
```
用java写1到20阶乘的和
可以使用以下代码来计算1到20阶乘的和:
```java
public static void main(String[] args) {
long sum = 0;
long factorial = 1;
for (int i = 1; i <= 20; i++) {
factorial *= i;
sum += factorial;
}
System.out.println("1到20阶乘的和为:" + sum);
}
```
输出结果为:2561327494111820313。
阅读全文