首页 > 编程语言 > 详细

Java实例——计算 1+2!+3!+...+20!的和

时间:2021-04-12 12:29:44      阅读:23      评论:0      收藏:0      [点我收藏+]

计算 1+2!+3!+...+20!的和

1、使用嵌套循环实现

 

public class FactorialAdd {
    public static void main(String[] args) {
        //计算 1+2!+3!+...+20!的和
        System.out.println(" 1+2!+3!+...+20!的和为:"+factAdd());

    }
    //使用嵌套循环计算 1+2!+3!+...+20!的和、
    public static int factAdd(){
        int sum = 0;
        for(int i = 1 ; i <= 20 ; i++){
            int result = 1;
            for(int j = 1 ; j <= i; j++){
                result *= j;
            }
            sum += result;
        }
        return sum;
    }
}

 

 

 

2、使用递归实现

 

public class FactorialAdd {
    public static void main(String[] args) {
        //计算 1+2!+3!+...+20!的和
        System.out.println(" 1+2!+3!+...+20!的和为:"+factAdd());

    }
    //和计算
    public static int factAdd(){
       int result = 0;
        for(int i = 1 ; i <= 20 ; i++){
            result += fact(i);
        }
        return result;
    }
    //阶乘计算
    public static int fact(int n){
       if(n == 1){
           return 1;
        }else{
            return n*fact(n-1);
        }
    }
}

 

Java实例——计算 1+2!+3!+...+20!的和

原文:https://www.cnblogs.com/lsm-boke/p/14646499.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!