采用递归和非递归实现阶乘,并计算和
#include<stdio.h>
long factorial(int n);
long factorial2(int n);//non-recursive
long sumOfFac(int n);
int main()
{
int n;
int i;
printf("input:");
scanf("%d",&n);
for(i = 1;i <= n;i ++)
{
printf("%d ! = %ld\n",i,factorial(i));
}
printf("sum of factorial 1 - %d: %ld",n,sumOfFac(n));
return 0;
}
long factorial(int n)
{
if(n == 1)
{
return 1;
}
else
{
return n * factorial(n - 1);
}
}
long factorial2(int n)
{
int i;
long result = 1;
for(i = 1;i <= n;i ++)
{
result *= i;
}
return result;
}
long sumOfFac(int n)
{
int i;
long sum = 0;
for(i = 1;i <= n;i++)
{
sum += factorial(i);
}
return sum;
}