这种题用递归或者迭代都可以,按自己喜欢的来:
迭代的算法:
public class Iteration{
public static void main(String[] args){
int s=0;
int s1;
for (int i=1;i<=20;i++){
s1=1;
for (int j=1;j<=i;j++){
s1=s1*j;
} s=s+s1;
}
System.out.println("1!+2!+...+20!="+s);
}
}
以下为递归算法:
public class Factorial{
public static void main(String[] args){
int s=0;
for (int i=1;i<=20;i++){
s=s+f(i);
}
System.out.println("1!+2!+3!+...20!="+s);
}
public static int f(int n){
if(n==1){
return 1;
}else if(n==0){
return 0;
}else if(n>1)
return f(n-1)*n;
else
System.out.println("输入有误!");
return -1;
}
}
迭代的算法:
public class Iteration{
public static void main(String[] args){
int s=0;
int s1;
for (int i=1;i<=20;i++){
s1=1;
for (int j=1;j<=i;j++){
s1=s1*j;
} s=s+s1;
}
System.out.println("1!+2!+...+20!="+s);
}
}
以下为递归算法:
public class Factorial{
public static void main(String[] args){
int s=0;
for (int i=1;i<=20;i++){
s=s+f(i);
}
System.out.println("1!+2!+3!+...20!="+s);
}
public static int f(int n){
if(n==1){
return 1;
}else if(n==0){
return 0;
}else if(n>1)
return f(n-1)*n;
else
System.out.println("输入有误!");
return -1;
}
}