java求1+2!+3!+… +20!的和
**阶乘:**从1到n的自然数相乘的积,用*n!*表示
eg:5!=1*2*3*4*5 0!= 1。
public class SueForPeace {
static void fun1() {
long num = 0, x = 1;
for (int i = 1; i <= 20; i++) {
x *= i;//相当于x = x*i
num += x;//相当于num = num+x
}
System.out.println("1+2!+3!+...+20!的和为:" + num);
}
static void fun2() {
long x = 0,y;
for(int i=1;i<=20;i++) {
y=1;
for(int j=1;j<=i;j++) {
y *= j;
}
x += y;
}
System.out.println("1+2!+3!+...+20!的和为:" + x);
}
public static void main(String[] args) {
fun1();
System.out.println("========嵌套循环========");
fun2();
}
}
运行结果: