美文网首页基础编程50题
【习题21】求阶乘的和

【习题21】求阶乘的和

作者: Xplorist | 来源:发表于2017-03-26 18:27 被阅读67次

【程序21】
题目:求1+2!+3!+...+20!的和

package com.share.test21_30;

/**
 * 【程序21】题目:<br>
 * 求1+2!+3!+...+20!的和 
 * 
 * @author brx
 */
public class Test21 {
    public static void main(String[] args) {
        test();
        test2();
    }

    /**
     * 思路1:<br>
     * 阶乘,第n个数乘以第前面n-1个数的积,递归思路,每一层都乘以该成的序列号,最后的结果就是从1乘到n
     */
    public static void test() {
        int sum = 0;
        for (int i = 1; i <= 20; i++) {
            sum += test1(i);
        }
        System.out.println("前20项阶乘的和为:" + sum);
    }

    // 递归
    public static int test1(int n) {
        int result = 1;
        if (n > 1) {
            result = n * test1(n - 1);
        }
        return result;
    }

    /**
     * 思路2:<br>
     * 不使用递归,将结果存进变量中然后递变
     */
    public static void test2() {
        int product = 1;
        int sum = 0;
        for (int i = 1; i <= 20; i++) {
            product *= i;
            sum += product;
        }
        System.out.println("前20项阶乘的和为:" + sum);
    }
}

相关文章

网友评论

    本文标题:【习题21】求阶乘的和

    本文链接:https://www.haomeiwen.com/subject/humkottx.html