/**
- 给定一个参数N,
- 返回: 1! + 2! + 3! + 4! + … + N! 的结果
*/
public class Factorial {
/**
* 每一次都单独算i的阶乘,再加上i-1的阶乘
* @param N
* @return
*/
public static long sumFactorial(int N){
long ans = 0;
for (int i = 1; i <= N; i++) {
ans += factorial(i);
}
return ans;
}
/**
* 计算i的阶乘
* @param i
* @return
*/
private static long factorial(int i) {
long ans = 1;
for (int i1 = 1; i1 <= i; i1++) {
ans*=i1;
}
return ans;
}
/**
* 用一个变量记住上一个数的阶乘,当前数的阶乘只需上一个数的阶乘再乘上当前数
* @param N
* @return
*/
public static long sumFactorial1(int N){
long ans = 0;
long tmpI = 1;
for (int i = 1; i <= N; i++) {
tmpI = tmpI*i ;
ans += tmpI;
}
return ans;
}
public static void main(String[] args) {
int N = 10;
System.out.println(sumFactorial(N));
System.out.println(sumFactorial1(N));
}
}
文章介绍了如何使用Java编程语言实现计算1到N的阶乘,提供了一个基础版本和一个优化版本,后者通过记忆上一个数的阶乘来提高效率。

被折叠的 条评论
为什么被折叠?



