编写一个java程序,计算1!+2!+3!+...+20!之和并在屏幕上输出

2024-12-01 04:18:55
推荐回答(5个)
回答1:

public class Factorials
{
public static void main(String args[])
{
long k,sum=0;
int i,j;
for(i=1;i<=20;i++)
{
k=1;
for(j=1;j<=i;j++)
k*=j;
sum+=k;
}
System.out.println("1!+2!+3!+……+20!="+sum);
}
}

回答2:

public class Test {
public static void main(String []args){
Haha haha=new Haha();
long sum=0;
for(int i=1;i<21;i++){
sum+=haha.jiechen(i);
}
System.out.print(sum);
}
}

class Haha{
public int jiechen(int i){
if(i==1){
return 1;
}else{
return i*jiechen(i-1);
}
}
}

回答3:

int sum = 0;
for(int i=1;i<=20;i++){
sum = sum + i;
}
System.out.println(sum);

回答4:

//20!好像没超出long值,不过还是用BigInteger吧
import java.math.BigInteger;
public class Main
{
public static void main(String args[])
{
int n=20;
BigInteger sum=new BigInteger("0");
BigInteger temp=new BigInteger("1");
for (int i=1;i<=n;i++)
{
temp=temp.multiply(new BigInteger(String.valueOf(i)));
sum=sum.add(temp);
}
System.out.println(sum);
}
}

回答5:

递归