I need to write a program "long int sum(int n)" which sum the total number of values like this:
1! − 2! + 3! − ... ± n!
I'm succesful with writing the sum for:
1-3 + 5 - ... ± (2n + 1)
float sum (int n) {
int max = 2*n +1, i = 1, sum = 0, ch = 2;
for (i = 1; i <= max; i+2; ){
if ((ch%2) == 0){
sum += i;
}
else{
sum = sum - i;
}
ch++;
return sum;
}
But I don't know/have an idea how to make it for a factorial sum.
it's useful to make another function that does the factorial and one that does the sum of the alternating series . . .
int factorial(int n)
{
int sum = 1;
if (n > 0)
for (int i = n; i > 1; --i)
sum *= i;
else if (n <= 0)
return 0;
return sum;
}
int alernatingSeriesSum(int nStart)
{
if(nStart < 1) return 0;
int sum = 0;
for(int i=1; i<nStart; ++i)
sum += (factorial(i) * ((i%2)==0 ? -1 : 1)); //multiply -1 if its an even #s
return sum;
}
the factorial is pretty straightforward, multiply by the value, decrement by one and iterate until it reaches 1.
the altnerating series sum is similiar, it calls factorial for reach iterating (except this time the index increases), and creates an alternating sign by mulitplying by -1 every time the index is even. this is how we produce 1! - 2! + 3! - 4! + . . . + (n+1)! - (n+2)!
i hope that helps . . .
if you cannot split it into functions, try writing this all in one main function . . . i tested this code in C and it works. feel free to play with the code and try to read what each line does. good luck.