计算 1+2!+3!+4!+...20!=?

package algs.factorial;

import java.math.BigInteger;

/**
 * Author: areful
 * Date: 2019/3/6
 * 计算 sum(n!), n=1,2, ... 20
 */
public class NFactorial {
    public static void main(String[] args) {
        System.out.println(calcFactorial0(3));
        System.out.println(calcFactorial1(3));
        System.out.println(calcFactorial2(3));

        System.out.println(calcFactorial0(50));
        System.out.println(calcFactorial1(50));
        System.out.println(calcFactorial2(50));
    }

    private static long calcFactorial0(int n) {
        long sum = 0L;
        long l = 1L;
        for (int i = 1; i <= n; i++) {
            l *= i;
            sum += l;
        }
        return sum;
    }

    private static double calcFactorial1(int n) {
        double sum = 0L;
        double l = 1L;
        for (int i = 1; i <= n; i++) {
            l *= i;
            sum += l;
        }
        return sum;
    }

    private static BigInteger calcFactorial2(int n) {
        BigInteger sum = BigInteger.valueOf(0L);
        BigInteger l = BigInteger.valueOf(1L);
        for (int i = 1; i <= n; i++) {
            BigInteger mul = BigInteger.valueOf(i);
            l = l.multiply(mul);
            sum = sum.add(l);
        }
        return sum;
    }
}

  运行结果:

 

posted on 2019-03-06 09:02  areful  阅读(840)  评论(0编辑  收藏  举报

导航