这种数列的求合算法一般都会有两种解法,一种是递归
static int CaculateFactorial(int n)
{
if (n == 1)
return 1;
int result = 1;
for (int i = 1; i <= n; i++)
result = result * i;
return result + CaculateFactorial(n - 1);
}
这种方法适合求n比较小的时候,算法简单易懂
另一种是用循环
static int CaculateFactorial1(int n)
{
if (n == 1)
return 1;
int result = 1;
int currentLoop;
for (int i = 2; i <= n; i++)
{
currentLoop = 1;
for (int j = 2; j <= i; j++)
{
currentLoop = currentLoop * j;
}
result += currentLoop;
}
return result;
}
这种算法适合比较大的数,由于不像递归要压栈出栈,运算速度要高很多
public int test(int x)
{
if (x <= 1)
{
return x;
}
else
{
int r = x;
for (int i=x-1; i>1; i--)
{
r *= i;
}
if (x > 1)
{
r += this.test(--x);
}
return r;
}
}
namingspcae SumFactorial{
public Class1{
public long Factorial(int n){
long a=1;
for(int i=n;i<=1;i--)
a*=i;
return a;
}
public long Sum(int n){
long b=0;
for(int j=1;j<=n;j++)
b+=Factorial(j);
return b;
}
}
}