获取1~n的阶乘之和
1
1*2
1*2*3
1*2*3*4
1的阶乘和 = 1的阶乘1
2的阶乘和 = 1的阶乘和 + 2的阶乘
3的阶乘和 = 2的阶乘和 + 3的阶乘
4的阶乘和 = 3的阶乘和 + 4的阶乘
5的阶乘和 = 4的阶乘和 + 5的阶乘
n的阶乘和 = (n-1)的阶乘和 + n的阶乘
package com.art.arithmetic.count;
public class OneToNFactorialSum {
public static void main(String[] args) {
OneToNFactorialSum otnFs = new OneToNFactorialSum();
System.out.println(otnFs.getFactorialSum(1));
System.out.println(otnFs.getFactorialSum(2));
System.out.println(otnFs.getFactorialSum(3));
System.out.println(otnFs.getFactorialSum(4));
System.out.println(otnFs.getFactorialSum(5));
long l = (long) 123;//10000111231231234124f;太大计算太久,Java默认直接书写的数字为int类型,范围是-2^31~2^31-1,所以需要转long才能输入更大的数字
System.out.println(otnFs.getFactorialSum(l));
}
/**
* 获取1~n的阶乘之和
* @param n
* @return
*/
public long getFactorialSum(long n) {
long sum = 0;
long factorial = 1;
for (long i = 1; i <= n; i++) {
factorial *= i; //计算阶乘
sum += factorial; //计算阶乘之和
}
return sum;
}
}