1
$\begingroup$

I got this series $S= (1^2 ) - (2^2 ) + (3^2 ) - (4^2 )+...+(-1)^{n+1 }* (n^2 )$

for( i = 1; i < n; i = i + n*n)
count++;
printf("The value of the series is:%d\n", count);

But i get either 1 or 4, i know im doing something really wrong since the series says add than subtract.

1 Answers 1

2

Well, something went wrong with your loop. It shoul be rather:

for(var i=1; i<=n; ++i)
   counter+=Pow(-1, n%2+1)*n^2;
print counter;

On the other hand, by looking on this problem in mathematical way...

See, that $n^2-(n+1)^2=-(2n+1)$. So: $$S_{2k}=1^2-2^2+3^2-4^2+...+(2k-1)^2-(2k)^2\\ =(1^2-2^2)+(3^2-4^2)+...+((2k-1)^2-(2k)^2) \\ = -3 - 5 -...-(4k+1) =-4\frac{k(k+1)}{2}=-2k(k+1)$$ and $$S_{2k+1}=S_{2k}+2k+1 = -2k^2-2k+2k+1=1-2k^2$$